我知道已经发布了与此类似的问题(例如Custom confirm dialog with JavaScript),但仍然找不到该问题的直接答案。
我目前在应用程序confirm dialogs
中有很多不同的事件。我使用浏览器内置的confirm('message')
函数来实现以下逻辑:
let answer = confirm('Are you sure you want to delete this?');
if(answert) { callDeleteFunction(); }
或
let answer = confirm('Are you sure you want to add this?');
if(answer) { callAddFunction(); }
等,但是我确实需要创建具有相同功能的自己的自定义确认功能。 (示例)
let answer = customConfirm('Are you sure you want to delete this?');
if(answert) { callDeleteFunction(); }
在customConfirm
函数将打开带有两个按钮的模态的情况下,根据单击的按钮,将从customConfirm
函数返回相应的值。我确实需要此功能,因为我在许多不同的地方都使用了confirm()
方法,因此实现了自定义确认功能,该功能将删除确认框的 accept / decline 返回值在我的项目中导致了很大的代码重构。目前,我正在做的是利用按钮中的回调,但是这里的问题是代码不会“冻结” 像内置的那样等待答案confirm()
函数可以。
我到目前为止所做的事情
function openConfirmModal(message, yesCallBack, noCallBack){
document.getElementById('confirmModal').style.display = 'block';
document.getElementById('confirmModalText').innerHTML = message;
let confirmModalYesBtn = document.getElementById('confirmModalYesBtn');
confirmModalYesBtn.addEventListener('click', function(event){
yesCallBack();
});
let confirmModalNoBtn = document.getElementById('confirmModalNoBtn');
confirmModalNoBtn.addEventListener('click', function(event){
noCallBack();
});
}
let answer = openConfirmModal( 'are you sure?', function () { return true; }, function () { return false; } );
// return answer; // ??
<!-- confirm modal classes and most of styling has been removed -->
<div id="confirmModal"style="width: auto; height: auto; visibility: visible; left: 737.688px; top: 354.813px; z-index: 1025; display: none;">
<div>
<span>Confirmation message</span>
<a href="#" id="confirmModalCloseBtn">
<span></span>
</a>
</div>
<div style="height: auto;">
<span></span>
<span id="confirmModalText"> </span>
</div>
<div>
<button id="confirmModalYesBtn">
<span></span>
<span>Yes</span>
</button>
<button id="confirmModalNoBtn">
<span></span>
<span>No</span>
</button>
</div>
</div>
问题是 answer变量在触发任何按钮之前就已返回,因此,是否有任何方法(甚至棘手)来“冻结”等待任何按钮单击的javascript线程?
预先感谢:)