我正在尝试开发一个插件,它将回调作为 init 的第一个参数。我尝试修改官方的插件代码tutorial 。我不明白为什么这里出了问题:
插件:
(function( $ ){
var methods = {
init : function( callback, options ) {
// Create some defaults, extending them with any options that were provided
var settings = $.extend( {
'location' : 'top',
'background-color' : 'blue'
}, options);
return this.each(function() {
$this.click(function(e) {
e.stopPropagation();
var $target = $(e.target);
if (callback)
callback($target);
});
});
},
};
$.fn.myplugin = 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.myplugin' );
}
};
})( jQuery );
调用插件:
// Create callback function
var callback = function(){alert('hey');};
$('#my-control').myplugin(callback,{'width':'600px'});
错误:
Method function (){alert('hey');} does not exist on jQuery.myplugin
最佳答案
这一行:
else if ( typeof method === 'object' || ! method ) {
导致 $.error
条件(在下一个 else
子句中)触发,因为您正在检查方法名称或选项对象,但没有' t 考虑传入函数类型的参数。
我建议将 callback
选项改为 options
对象的一部分:
(function($) {
var methods = {
init: function(options) {
console.dir(arguments);
// Create some defaults, extending them with any options that were provided
var settings = $.extend({
'location': 'top',
'background-color': 'blue'
}, options);
return this.each(function() {
$(this).click(function(e) {
e.stopPropagation();
var $target = $(e.target);
if (settings.callback) settings.callback($target);
});
});
},
};
$.fn.myplugin = 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.myplugin');
}
};
})(jQuery);
用法:
var callback = function(){alert('hey');};
$('#my-control').myplugin({'width':'600px', callback: callback});
关于jquery - 将回调传递给我的 jquery 插件时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9620773/