微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决没有库的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

解决方法

您需要稍微更改代码并使用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')
            }
        });

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。