我有一个jquery ui对话框,我想用来提示用户确认删除。当用户按“是”或“否”时,我需要返回“True”或“False”继续执行一些javascript。下面的代码的问题是当对话框显示它立即执行“return true;”但用户还没有按“是”按钮?
我究竟做错了什么?
HTML:
<div id="modal_confirm_yes_no" title="Confirm"></div>
Javascript调用:
$("#modal_confirm_yes_no").html("Are you sure you want to delete this?"); var answer = $("#modal_confirm_yes_no").dialog("open"); if (answer) { //delete } else { //don't delete }
Jquery对话框
$("#modal_confirm_yes_no").dialog({ bgiframe: true,autoOpen: false,minHeight: 200,width: 350,modal: true,cloSEOnEscape: false,draggable: false,resizable: false,buttons: { 'Yes': function(){ $(this).dialog('close'); return true; },'No': function(){ $(this).dialog('close'); return false; } } });
解决方法
javascript是异步的
所以你必须使用回调:
$("#modal_confirm_yes_no").dialog({ bgiframe: true,buttons: { 'Yes': function(){ $(this).dialog('close'); callback(true); },'No': function(){ $(this).dialog('close'); callback(false); } } }); function callback(value){ //do something }