使用JavaScript自定义确认对话框
我想创建一个类似于confirm()
的JavaScript函数,它显示一个对话框(带有问题和2个按钮的div),如果用户单击“确定”则返回true
否则返回false
。
是否可以使用JavaScript / jQuery但没有插件(例如jQuery UI或Dialog)? 因为我正在努力减少尺寸和往返时间……
我试着编写这段代码,但我不知道如何让用户点击这个函数“等待”。
我想以这种方式使用我的函数:
answer=myConfirm("Are you sure?")
通过这种方式,我可以在几个上下文中使用相同的函数,只需更改作为参数传递的问题。 这与confirm()的行为相同
在等待用户输入然后从函数返回时,在JavaScript中更常见的是提供一个回调函数,该函数将在您等待的操作完成时调用。 例如:
myCustomConfirm("Are you sure?", function (confirmed) { if (confirmed) { // Whatever you need to do if they clicked confirm } else { // Whatever you need to do if they clicked cancel } });
这可以通过以下方式实施:
function myCustomConfirm(message, callback) { var confirmButton, cancelButton; // Create user interface, display message, etc. confirmButton.onclick = function() { callback(true); }; cancelButton.onclick = function() { callback(false); }; }
如果使用jQuery,为什么不实现jQueryUI ? 并使用Dialog函数如下:
作为2部分:
HTML
Are you sure?
脚本
$( "#dialog-confirm" ).dialog({ resizable: false, modal: true, buttons: { "OK": function() { $( this ).dialog( "close" ); }, Cancel: function() { $( this ).dialog( "close" ); } } });
所有脚本:
$(function() { $("").attr("id", "dialog-confirm").append( $("").text('Are you sure?').css("text-align", "center").prepend( $("").addClass("ui-icon ui-icon-alert").css({ float: 'left', margin: '0 7px 20px 0' }) ) ).dialog({ resizable: false, modal: true, title: "ALERT", buttons: { "OK": function() { answer=1; $(this).dialog("close"); }, "Cancel": function() { answer=0; $(this).dialog("close"); } } }); });
的jsfiddle
这真的应该通过回调来完成。 与您所追求的最接近的是使用发布和订阅模型以及一些自定义事件。
为此:
当用户单击“是”按钮时,触发名为clickedYes的自定义事件。 为“不”做同样的事情
$('#yesbtn').click(function(){ $(document).trigger('clickedYes'); }); $('#nobtn').click(function(){ $(document).trigger('clickedNo'); });
现在我们需要“监听”或订阅这些事件并在上下文中执行适当的操作。
让我们创建一个假设的情况 :您的用户单击删除,您想确认该选择。
首先设置你想要发生的事情,如果他们点击是:
$(document).unbind('clickedYes'); //Unbind any old actions $(document).bind('clickedYes',function(){ //Code to delete the item //Hide the popup });
然后如果他们点击否你想要发生什么:
$(document).unbind('clickedNo'); //Unbind any old actions $(document).bind('clickedNo',function(){ //Hide the popup and don't delete });
因此,我们设置了正在侦听clickedYes或clickedNo的操作。 现在我们只需要向用户显示弹出窗口,以便他们必须单击是或否。 当他们这样做时,他们将触发上述事件。
所以你的myConfirm()函数将执行以下操作:
function myConfirm(msg){ //change the message to 'msg' //Show the popup }
所以订单将是:
- 将自定义事件的触发器绑定到是和否按钮
- 在提示之前 – 取消绑定任何旧操作并附加新操作
- 向用户显示一个弹出窗口,使其触发您的操作。
这将允许你调用这样的函数myConfirm(’你确定’); 这不是你想要的……但我认为不可能完全按照自己的意愿行事。