0

我有一个带有可选参数的简单 jQuery 函数,我想要的只是传递控件名称、事件名称和值或函数名称,而不是将其绑定到传递的控件。

jQuery 函数

BindEvents: function (options) {

    var defaults = {
        Control: null,
        Events: null
    }
    settings = $.extend({}, defaults, options);

    if (Events != null) {
        $(Control).on(Events['name'], function () {
            'How to call passed function';
        });
    }
}

调用函数

$.fn.BindEvents({
    Control: "#txtTest",
    Events: { "name": "focus", "value": "$.fn.test()" }
});
4

1 回答 1

0

1)您忘记使用“设置”前缀:

BindEvents: function (options) {
    // defaults do not make sense this way, but they probably have a sane default in your code, right?
    var defaults = {
        Control: null,
        Events: null
    }
    settings = $.extend({}, defaults, options);

    if (settings.Events != null) {
        $.each(settings.Events, function(eventName, handler) {
            $(settings.Control).on(eventName, handler);
        });
    }
}

2) 使用函数引用而不是字符串调用 BindEvents。我还稍微更改了 Event 对象:

$.fn.BindEvents({
    Control: "#txtTest",
    Events: { "focus": $.fn.test }
});
于 2013-10-29T20:12:30.667 回答