我有一个带有可选参数的简单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()" }
});
答案 0 :(得分:0)
1)您忘记使用'settings'前缀:
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 }
});