差不多三年后,我正在寻找类似的东西。由于我还没有找到一个可接受的“快速”解决方案,我写了一些非常接近 OP 标准的东西。我认为其他人将来可能会发现它很有用。
JavaScript 是事件驱动的,这意味着它不支持我们可以用来暂停纯 JavaScript 确认函数的任何类型的“等待”或“睡眠”循环。这些选项包括消耗处理器周期、使用浏览器插件或 AJAX。在我们日益移动的世界中,有时互联网连接参差不齐,这些都不是很好的解决方案。这意味着我们必须立即从“确认”函数返回。
但是,由于上面的代码片段中没有“假”逻辑(即用户点击“取消”时什么都不做),我们可以在用户点击“确定”时再次触发“点击”或“提交”事件。 " 为什么不在我们的“确认”函数中设置一个标志并根据该标志做出反应?
对于我的解决方案,我选择使用 FastConfirm 而不是“模态”对话框。您可以轻松地修改代码以使用您想要的任何内容,但我的示例旨在使用它:
https://github.com/pjparra/Fast-Confirm
由于这样做的性质,我看不到一个干净的方式来打包它。如果您觉得这有太多粗糙的边缘,请随意平滑它们或按照其他人推荐的方式重写您的代码:
/* This version of $.fn.hasEvent is slightly modified to provide support for
* the "onclick" or "onsubmit" tag attributes. I chose this because it was
* short, even if it is cryptic.
*
* Learn more about the code by Sven Eisenschmidt, which is licensed under
* the MIT and GPL at:
* http://github.com/fate/jquery-has-event
*/
(function($) {
$.fn.hasEvent = function(A, F, E) {
var L = 0;
var T = typeof A;
E = E ? E : this;
var V = (E.attr('on'+A) != undefined);
A = (T == 'string') ? $.trim(A) : A;
if (T == 'function')
F = A, A = null;
if (F == E)
delete(F);
var S = E.data('events');
for (e in S)
if (S.hasOwnProperty(e))
L++;
if (L < 1)
return V; // = false;
if (A && !F) {
return V = S.hasOwnProperty(A);
} else if(A && S.hasOwnProperty(A) && F) {
$.each(S[A], function(i, r) {
if(V == false && r.handler == F) V = true;
});
return V;
} else if(!A && F) {
$.each(S, function(i, s) {
if (V == false) {
$.each(s, function(k, r) {
if (V == false && r.handler == F)
V = true;
});
}
});
}
return V;
}
$.extend($, {hasEvent: $.fn.hasEvent});
}) (jQuery);
/* Nearly a drop-in replacement for JavaScript's confirm() dialog.
* Syntax:
* onclick="return jq_confirm(this, 'Are you sure that you want this?', 'right');"
*
* NOTE: Do not implement "false" logic when using this function. Find another way.
*/
var jq_confirm_bypass = false;
function jq_confirm(el, question, pos) {
var override = false;
var elem = $(el);
if ($.fn.fastConfirm == undefined) {
override = confirm(question);
} else if (!jq_confirm_bypass) {
if (pos == undefined) {
pos = 'right';
}
elem.fastConfirm({
position: pos,
questionText: question,
onProceed: function(trigger) {
var elem = $(trigger);
elem.fastConfirm('close');
if (elem.hasEvent('click')) {
jq_confirm_bypass = true;
elem.click();
jq_confirm_bypass = false;
}
if (elem.hasEvent('submit')) {
jq_confirm_bypass = true;
elem.submit();
jq_confirm_bypass = false;
}
// TODO: ???
},
onCancel: function(trigger) {
$(trigger).fastConfirm('close');
}
});
}
return override ? override : jq_confirm_bypass;
}
所以... onclick="return confirm('你想测试这个吗?');" 会变成 onclick="return jq_confirm(this, 'Do you want to test this?');" pos/"right" 参数是可选的,专门用于快速确认。
当您单击时,jq_confirm() 函数将生成 jQuery 对话框并返回“false”。当用户单击“确定”时,jq_confirm() 设置一个标志,调用原始单击(或提交)事件,返回“true”,然后取消设置标志以防您想留在同一页面上。