在JQuery中执行顺序对话框



我试图使用JQuery对话框来确认从不同的表中删除不同的记录,所以它是从代码中的不同地方引用的div(重用对话框来确认不同的操作)。我使用这个例子:http://jqueryui.com/dialog/#modal-confirmation

由于每次调用都必须确认一个非常不同的操作,因此我不能只将要执行的代码放在Dialog选项按钮{}的Ok或Cancel按钮的回调中

我想有一些像VB的MsgBox的返回值指示按下按钮(无论是'Ok', '接受'或'关闭'…)。像这样:

if ( $(target_dialog).dialog('open') == 'Ok'){
    // Do something awesome
}else if( $(target_dialog).dialog('open') == 'Cancel') {
    // Do something not that awesome
}

谢谢你的帮助。

编辑:这有点像JS确认()的例子在这里(http://www.w3schools.com/js/tryit.asp?filename=tryjs_confirm),但我不希望它是一个弹出,但一个可定制的和灵活的jqueryui对话框。

编辑2:就像@vishwanath建议的那样

$("#dialog-confirm").dialog({
//height, modal, width... settings
buttons : {
    "OK": function() { 
        // here is the magic
            action = $(this).data('action');
        var actionToPerform = actions[action];
        actionToPerform.call(this);
        // end of magic
        $( this ).dialog( 'close' );
    }, 
    Cancel: function() {
        console.log("non awesome stuff here");
        $( this ).dialog( 'close' );
    }
}
});

var actions = {
action1 : function(){
    console.log(''Do action1 stuff here);
}, 
action2 : function(){
    console.log('Do action2 stuff here');
}
// and so on...
}

不同的家长对不同的答案可以采取不同的行动。

$( '#dlgConfirm' ).data('action', 'action1').dialog( 'open' );

谢谢。

一个可能的解决方案是使用jquery UI的自定义选项。

如下所示,创建一个模式自定义选项,该选项将在对话创建时动态设置。在单击处理程序中检查该选项,并根据您的模式使用该模式来选择正确的操作。

var mode = 'edit'; //Set this dynamically
$("#dialog-confirm").dialog({
    height : 140,
    modal : true,
    mode : mode,
    buttons : [ {
        text : "OK",
        click : function(event) {
            var mode = $("#dialog-confirm").dialog('option', mode);
            var actionToPerform = actions[mode];
            actionToPerfom.call(this, event);
        }
    }, 
    {
        text : "Cancel",
        click : function(event, ui) {
            console.log("non awesome stuff here");
        }
    } ]
});

var actions = {
    edit : function(){
        console.log(''Do Edit stuff here);
    }, 
    delete : function(){
        console.log('Do delete stuff here');
    }
}

你可以使用Promises(又名"deferred objects")来模拟一个在对话框关闭后返回值的函数。将它与模态对话框结合使用,以确保用户在对话框关闭之前不能做任何其他事情:

function myConfirm() {
    my def = $.Deferred();
    $('#myDiv').dialog({
       modal: true,
       buttons: [ {
           'ok': def.resolve,
           'cancel': def.reject
       } ]
    });
    return def.promise();
}

(添加用于参数化对话框的代码)

:

myConfirm().done(function() {
    // user pressed OK
}).fail(function() {
    // user pressed Cancel
});

最新更新