将函数名称附加到JQuery对话框按钮

时间:2013-02-02 17:12:51

标签: jquery-ui jquery-ui-dialog

我正在使用JQuery Dialog创建一个对话框插件。以下是可以传递的参数。它包括用户想要添加的按钮文本,并回调函数名称,该名称将在单击该按钮时执行。

    var settings = $.extend({
        message: 'Your action is successful',
        title: 'Message',
        showButton: true,
        buttonText: 'OK',
        onButtonClick: 'OnButtonClick',
        allowClose: true
    }, options);

我遇到了将该功能名称附加到按钮事件的问题。我正在尝试做类似下面的事情,但它会引发错误。

    $('#dialog-message').dialog({
        buttons: [{
            text: settings.buttonText,
            click: window[settings.onButtonClick]()

        }],
        closeOnEscape: true,
        close: function (e) {
            $(this).empty();
            $(this).dialog('destroy');
    }
    });

任何建议如何将该功能名称附加到单击事件,因为我只有函数名称。

1 个答案:

答案 0 :(得分:0)

插件的调用者应该为onButtonClick选项而不是字符串提供回调。像这样:

function OnButtonClick(){
   //does some cool stuff
}

var settings = $.extend({
    message: 'Your action is successful',
    title: 'Message',
    showButton: true,
    buttonText: 'OK',
    onButtonClick: OnButtonClick,
    allowClose: true
}, options);

然后你可以像这样绑定传入的函数:

$('#dialog-message').dialog({
    buttons: [{
        text: settings.buttonText,
        click: settings.onButtonClick
    }],
    closeOnEscape: true,
    close: function (e) {
        $(this).empty();
        $(this).dialog('destroy');
    }
});

这是可能的,因为onButtonClick变量现在通过他们用来初始化插件的settings来保存对插件用户提供的回调的引用(而不是字符串)。 / p>

希望有所帮助!

相关问题