我正在尝试创建多个对话框以及一些我无法理解如何创建这些对话框的方法。
每个对话框都有DIV's
,其中包含每个操作的消息。基本上,如果用户选中CheckBox
,则会出现一个对话框,说明您要确认此操作。一段时间后如果用户再次取消选中CheckBox
,则会出现另一个带有diff消息的对话框。请帮帮我。
这是我到目前为止所得到的。
===============
<div id="dialog-isReceived" title="Mark as Received?">
Are you sure you want to mark this order as "Received"? <br />
The customer will receive an email confirming their order is ready for collection.
</div>
<div id="dialog-notReceived" title="Mark as Not Received?">
Are you sure you want to mark this order as "Not Received"? <br />
</div>
var isReceivedCheckBox = $('.isReceivedCheckBox input[type=checkbox]');
var dialogId; //trying to pass the Id of the div dynamically BUT not working
var result;
$(document).ready(function () {
$(dialogId).dialog(
{
autoOpen: false,
width: 300,
height: 200,
resizable: false,
modal: false,
buttons: {
"Confirm": function () {
result = true;
},
Cancel: function () {
result = false;
$(this).dialog("close");
}
},
});
});
=====================
$(document).on("change",isReceivedCheckBox, function () {
var checked = $(this).is(':checked');
if (checked) {
dialogId = "'#dialog-isReceived'"; //setting the DIV ID here and hoping that dialog will appears.
$(dialogId).dialog('open');
if(!result)
$(this).attr("checked", false); // if user clicks cancel on dialog then do not check the checkbox
} else {
dialogId = "'#dialog-notReceived'";
$(dialogId).dialog('open');
if(!result)
$(this).attr("checked", true); //if user clicks cancel on dialog then do not uncheck the checkbox because it was checked previously
}
});
这里的问题是对话框永远不会出现,因为当页面加载时我的所有div都是可见的,因为我无法在页面加载时设置dialogID
变量。此外,我在此页面上至少有5个对话框执行相同的功能。如果你可以建议更好的方法,或者告诉我我在做什么,这将是非常好的和赞赏。
感谢, 米兰P
答案 0 :(得分:1)
你的方法的另一个可能的问题是jQuery对话是异步的,这意味着条件
if(!result)
将在用户有时间确认或取消对话框之前评估。如果你想要的是模仿使用对话框确认javascript的行为,你需要使用jQuery Deferred对象。此外,我建议根据需要创建和销毁对话框,如:
function confirmDialog(msg) {
var dialog = $("<div>"+msg+"</div>");
var def = $.Deferred();
$(dialog).dialog({
autoOpen: true,
width: 300,
height: 200,
resizable: false,
modal: false,
buttons: {
'Confirm': function() {
def.resolve();
$( this ).dialog( "close" );
},
'Cancel': function() {
def.reject();
$( this ).dialog( "close" );
}
},
close: function () {
if (def.state() === "pending") {
def.reject(); // Make sure unanswered dialog rejects
}
$( this ).remove();
}
});
return def.promise();
}
然后像这样称呼它:
confirmDialog("are your sure?").done(function() {
// He/She said yes
}).fail(function() {
// He/She said no
});
阅读更多关于jQuery的更多内容http://api.jquery.com/category/deferred-object/
小提琴:http://jsfiddle.net/fGQTj/
编辑:固定代码,添加小提琴