不带库的JavaScript自定义确认函数
我正在尝试创建没有库的自定义确认函数。 该函数显示返回不带库的JavaScript自定义确认函数,javascript,asynchronous,async-await,Javascript,Asynchronous,Async Await,我正在尝试创建没有库的自定义确认函数。 该函数显示返回true或false if(getConfirmation) { do something } else { do something } 除了使用按钮,一切都已完成。我遇到的问题是,我无法以默认confirm函数的方式停止代码执行。单击按钮(单击我)(第56行)后,我立即收到未定义或取消,该按钮必须执行获取确认功能 const button = document.querySelector('#abc') button.a
true
或false
if(getConfirmation) {
do something
} else {
do something
}
除了使用按钮,一切都已完成。我遇到的问题是,我无法以默认confirm
函数的方式停止代码执行。单击按钮(单击我
)(第56行)后,我立即收到未定义
或取消
,该按钮必须执行获取确认
功能
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
)
演示在这里:您需要稍微更改代码并使用承诺
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);
})
});
};
}
如果您想使用
async
/await
,当按钮被点击时,它应该实现的承诺在哪里?老实说,我不知道如何以async/await
的方式检测按钮的点击,我尝试了一些方法,但无法解决它。这就是我来这里的原因:(
getConfirmation(options)
.then(result => {
if (result) {
console.log('Ok')
} else {
console.log('Cancel')
}
});