如何解决没有库的JavaScript自定义确认功能
我正在尝试在不使用库的情况下进行自定义确认功能。
该函数显示模式窗口和返回true
或false
if(getConfirmation) {
do something
} else {
do something
}
除使用按钮外,所有步骤均已完成。我有一个问题,我无法以默认confirm
函数的工作方式停止执行代码。在单击必须执行undefined
功能的按钮(Cancel
)(第56行)之后,我收到Click me
或getConfirmation
。
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
})
})
}
问题:如何等待按钮(Confirm
或Cancel
)被点击?
演示在这里: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 举报,一经查实,本站将立刻删除。