条件按钮添加到jQuery模式

And*_*aal 9 jquery modal-dialog

我有一个jQuery模式,如果满足条件语句,我想添加一个额外的按钮.

原始示例代码(缩减):

$("#dialog").html("<div></div>").dialog({
    title: "Some Title",
    modal: true,
    width: 550,
    buttons: {
        Ok: function() {
            //
        },
        'A Button': function() {
            //
        }
    }
}).dialog('open');
Run Code Online (Sandbox Code Playgroud)

因此,正如您在上面看到的那样,有一个带有2个按钮的模态,但我还想添加一些动态代码,以便在设置变量时能够满足额外的按钮.例如

var some_variable = 0;

$("#dialog").html("<div></div>").dialog({
    title: "Some Title",
    modal: true,
    width: 550,
    buttons: {
        Ok: function() {
            //
        },
        'A Button': function() {
            //
        }
        /* ??? */
        if (some_variable==1) //then add the other button's code here..
        /* ??? */
    }
}).dialog('open');
Run Code Online (Sandbox Code Playgroud)

Jam*_*ice 17

您可以buttons在创建对话框之前创建对象:

//Create the buttons object
var buttons = {
    Ok: function() {},
    'A Button': function() {}
};

//Add another button to that object if some condition is true
if(something) {
    buttons['B button'] = function() {};
}

//Create the dialog, passing in the existing buttons object
$("#dialog").html("<div></div>").dialog({
    buttons: buttons,
    //Other options
});
Run Code Online (Sandbox Code Playgroud)