1
在编写插件时,如何传递基于事件的可选函数。我可以通过在调用过程中将函数的名称手动编写为字符串,然后将其作为字符串中的onclick =“”添加到this.html()中,但这是naff。我想成熟传递函数作为可选参数,并选择将其添加为点击条件事件jQuery插件 - 在选项中传递函数 - 但作为事件触发
文档
<div id="grid"></div>
<script>
$(function() {
$("#grid").myaddon({
"headings" : [
{
"title" : "hello",
"click_callback" : function(){
alert('hi');
}
},
{
"title" : "there"
}
]
});
});
</script>
和插件本身
(function($) {
var methods = {
init : function(options) {
var defaults = {
"title": "text",
"click_callback": function() {}
}
for(var i=0; i<options.headings.length; i++) {
var heading = $.extend({},defaults,options.headings[i]);
this.html("<div id=\"addon"+(parseInt(i))+"\" >" + heading.title + "</div>");
if (typeof heading.click_callback == 'function') {
$("#addon"+(parseInt(i))).click(function() { heading.click_callback.call(this) }); //this doesn't work
$("#addon"+(parseInt(i))).click(function() { heading.click_callback.call() }); //this doesn't work
$("#addon"+(parseInt(i))).click(heading.click_callback.call()); //this doesn't work
$("#addon"+(parseInt(i))).click(eval(heading.click_callback.call())); //(in desperation) this doesn't work
//(edit)
$("#addon"+(parseInt(i))).click(heading.click_callback); //(!!thanks Robert Fricke!) thanks to the answer from Robert Fricke I know this works
//(/edit)
}
}
}
}
$.fn.myaddon = function(method) {
// Method calling logic
if (methods[method]) {
return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1));
}
else if (typeof method === 'object' || ! method) {
return methods.init.apply(this, arguments);
}
else {
$.error('Method ' + method + ' does not exist on jQuery.myaddon');
}
};
})(jQuery);
哇! '$(“#addon”+(parseInt(i)))。click(heading.click_callback);'谢谢,做过了......可能太明显了,不能试试谢谢! – user2083181 2013-02-18 13:10:32