没有库的JavaScript自定义确认功能

我正在尝试在不使用库的情况下进行自定义确认功能。 该函数显示模式窗口和返回truefalse

的按钮
if(getconfirmation) {
    do something
} else {
    do something
}

除使用按钮外,所有步骤均已完成。我有一个问题,我无法以默认confirm函数的工作方式停止执行代码。在单击必须执行undefined功能的按钮(Cancel)(第56行)之后,我收到Click megetconfirmation

const button = document.querySelector('#abc')
button.addEventListener('click',(e) => {
    // usage
    if(getconfirmation(options)) {
        console.log('Ok')
    } else {
        console.log('Cancel')
    }
})

代码看起来像这样,我认为这是我检测点击次数的方式。

function getconfirmation(options) {
    const element = createElement('confirm_window')
    element.insertAdjacentHTML('afterbegin',getTemplate(options))
    document.body.appendChild(element)
    
    element.querySelectorAll('button').forEach(button => {
        button.addEventListener('click',function(e) {
            const result = options.buttons.find(b => b.name === e.target.name).result
            document.body.removeChild(element)
            return result
        })
    })
        
}

问题:如何等待按钮(ConfirmCancel)被点击?

演示在这里:https://codepen.io/hamper_/pen/eYzNXqN?editors=1010

sdaSDWDADW 回答:没有库的JavaScript自定义确认功能

您需要稍微更改代码并使用Promise

function getConfirmation(options) {
    return new Promise(resolve => {
        const element = createElement('confirm_window')
        element.insertAdjacentHTML('afterbegin',getTemplate(options))
        document.body.appendChild(element)

        element.querySelectorAll('button').forEach(button => {
            button.addEventListener('click',function(e) {
                const result = options.buttons.find(b => b.name === e.target.name).result
                document.body.removeChild(element)
                resolve(result);
            })
        });
    };      
}
    getConfirmation(options)
        .then(result => {
            if (result) {
                console.log('Ok')
            } else {
                console.log('Cancel')
            }
        });
本文链接:https://www.f2er.com/1409044.html

大家都在问