【发布时间】:2017-10-23 07:06:06
【问题描述】:
我正在使用 jQuery UI 显示一个对话框,询问“你真的要执行这个操作吗?”当用户点击超链接或表单按钮时。
如果用户点击“确认”,那么我想执行原来的默认操作。
这是我的代码:
[html]
<a href="page.htm">Click me</a>
[jquery]
// Global variable keeps track of whether the user has clicked confirm
var confirmed = false;
$("a").on("click", function(e) {
var self = $(this);
var options = {
autoOpen: true,
modal: true,
title: "Confirmation Required",
buttons : {
"Confirm" : function() {
// The user has confirmed, so set global variable to true
confirmed = true;
// Re-trigger the click
self.trigger("click");
},
"Cancel" : function() {
$(this).dialog("close");
}
}
};
// If the user hasn't yet confirmed, display the dialogue box
if (confirmed == false) {
$("<div />").text("Are you sure you want to do this?").dialog(options);
// Prevent the default action
e.preventDefault();
}
// Otherwise the user has confirmed, so don't preventDefault and return true
else {
confirmed = false;
// Alert here to check we reached this point
alert("Returning true");
return true;
}
});
第一次点击链接时,会阻止默认操作并打开对话框。
单击对话框中的“确认”时,再次触发单击事件,并触发警报框,提示“返回真”。到目前为止一切都很好,但是页面没有加载。因此,由于某种原因,第二次默认事件仍然被阻止,我一生都无法弄清楚原因。
【问题讨论】:
标签: javascript jquery jquery-ui preventdefault