[英]how to use jquery UI dialog as javascript confirm?
我读了很多关于这个的问题,但是每个解决方案都使用相同的解决方法,在jquery对话框中提交表单,如下所示:
$("#dialog").dialog({
buttons : {
"Confirm" : function() {
window.location.href = targetUrl;
},
"Cancel" : function() {
$(this).dialog("close");
}
}
是不是有更简单的方法,更像是javascript确认?
<input type="submit" onclick="return confirm('are you sure?');" />
为什么返回true,返回false不起作用?
这是您可以做的,您将输入类型从“提交”更改为“按钮”,然后,您可以像这样使用您的脚本:
$(document).ready(function(){
$("#dialog").dialog({
autoOpen: false,
buttons : {
"Confirm" : function() {
$('#form1').submit();
},
"Cancel" : function() {
$(this).dialog("close");
}
}
});
$('#submitButton').click(function(){
$("#dialog").dialog('open');
});
});
这样,只有在使用确认对话框时才会提交表单。
在您的情况下返回false或true无关紧要的原因是对话框刚刚显示,但submit事件中的代码将继续执行,除非您在显示对话框后返回false。
我编写了以下代码,使用JQuery的UI Dialog作为模态确认。 通过事件目标提交表单,不会对递归事件处理程序进行递归调用。
$(function () {
$('form[action*="/Delete"]').submit(function (e) {
e.preventDefault();
$("<div>Are you sure you want to delete this?</div>").dialog({
resizable: false,
height: 140,
modal: true,
buttons: {
Ok: function () {
e.target.submit();
},
Cancel: function () {
$(this).dialog("close");
}
}
});
});
});
这是因为jQuery UI对话框在技术上不是模态的,与confirm
和alert
不同。 他们不会暂停你正在执行的javascript。 但你可以得到基本相同的东西:
function restOfTheCode(returnValue)
{
//do stuff
}
$("#dialog").dialog({
buttons : {
"Confirm" : function() { $(this).dialog("close"); restOfTheCode(true); },
"Cancel" : function() { $(this).dialog("close"); restOfTheCode(false); }
}
});
//anything down here executes immediately after the dialog is shown, so that's no good.
相当于:
var returnValue = confirm("Are you sure you want to confirm?");
//do stuff
编辑:好的,添加提交问题,这里的备用代码没有任何意义。 但解释是一样的:它不是模态的。 如果你真的想,你可以模拟这个:
function modalDialogConfirm()
{
var buttonClicked = false;
var valueSelected;
$("#dialog").dialog({
buttons : {
"Confirm" : function() { $(this).dialog("close"); buttonClicked = true; valueSelected = true; },
"Cancel" : function() { $(this).dialog("close"); buttonClicked = true; valueSelected = false; }
}
});
function y { setTimeOut("x()", 100); }
function x { setTimeOut("y()", 100); }
while(!buttonClicked);
return valueSelected;
}
...但这只会冻结浏览器,所以它不是很有用......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.