【发布时间】:2011-04-03 10:00:55
【问题描述】:
我使用jQuery UI dialog 在单击按钮时显示确认对话框。我想在点击确定时返回true,否则返回false。
在onClick(如给定here,$dialog.dialog('open');)事件中关联对话框打开调用不起作用。因此,作为一种解决方法,我采用了一种类似于此的方法:http://www.perfectline.co.uk/blog/unobtrusive-custom-confirmation-dialogs-with-jquery。这种方法和我的方法有两个不同:
- 该示例使用锚标记,
- 它不使用 jQuery UI 对话框。
我已经修改了示例链接中给出的代码,但它不起作用。我想知道我做错了什么。有没有更便宜的方法来做到这一点?
这里是代码,所有的CSS/JS都引用了jQuery CDN,所以你应该可以复制代码来看看行为。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/themes/blitzer/jquery-ui.css" rel="stylesheet" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Control Panel</title>
</head>
<body>
<form action="http://google.com">
<button class="es-button ui-state-default ui-corner-all" name="changeSem" id="id2">Start Thermonuclear War</span>
</button>
</form>
<div title="Why so serious?" id="id3" style="display:none;">
<p>You are about to start a war.
<p>Click OK to confirm. Click Cancel to cancel this action.</p>
</div>
</body>
<script type="text/javascript">
$('#id2').click(function (event) {
if ($(this).data('propagationStopped')) {
//alert('true');
$(this).data('propagationStopped', false);
return true;
} else {
event.stopImmediatePropagation();
$('#id3').dialog({
//autoOpen: false,
width: 600,
buttons: {
"Ok": function () {
$(this).dialog("close");
$('#id2').data('propagationStopped', true);
$('#id2').triggerHandler(event);
},
"Cancel": function () {
$(this).dialog("close");
return false;
}
}
});
//alert('false');
return false;
}
});
</script>
</html>
澄清:请注意,提交表单非常简单(参见solution by bryan.taylor)。我在这里要做的是通过单击按钮来模拟提交。更像是 JavaScript 的 confirm() 方法。
【问题讨论】:
-
理想情况下,此示例应将您带到 Google 上 OK 并关闭,而在 Cancel 上不执行任何操作。我会尽量避免明确的基于 $(formName).submit() 的解决方案。
标签: javascript jquery html jquery-ui