我正在尝试制作一个自定义复选框和单选按钮的jQuery插件。
(function($)
{
$.fn.checkboxRadio = function(options)
{
var defaults = some;
...
return this.each(function()
{
var button = $(this);
...
});
}
})(jQuery);现在$('input').checkboxRadio(options);就可以使用它了
如何在不改变当前作用域的情况下添加方法check,以便尽可能地使用$('input').checkboxRadio('check')之类的东西
如何处理自定义方法并在我的插件中获得它的名称?
发布于 2013-01-31 06:12:15
这是官方的jquery plugin guide。
有关包装函数的部分可以在here ("Plugin Methods")中找到(示例是一个潜在的工具提示插件):
(function( $ ){
var methods = {
init : function(options) { ... },
show : function() { ... },
hide : function() { ... },
update : function(content) { ... }
};
$.fn.tooltip = 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.tooltip' );
}
};
})(jQuery);更新解释了指南中的methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ))行:
如果从javascript代码中调用$(selector).tooltip('update', 'hello'),您希望最终调用update方法,将'hello'作为content参数传递,并在调用期间将this设置为$(selector)。
这就是这一行所要做的:
method == 'update',methods[method]是update方法,则['update', 'hello']将等于['update', 'hello'],则必须删除第一个元素以获取要传递给方法的参数;这正是Array.prototype.slice.call(arguments, 1)所做的,have调用函数myFunc,将argsArray作为参数传递,并在调用期间将<代码>D27设置为<代码>D28。<代码>H229<代码>F230因此,在你的方法中,你可以调用this.each(...)来迭代所有选择器的项,例如:
update: function(content) {
this.each(function(){ $(this).data('tooltip.content', content); });
return this;
}发布于 2013-01-31 06:09:04
你可以像这样连接插件方法:
(function($) {
$.fn.checkboxRadio = function(options) {
var defaults = {
check: 'check'
}
return this.each(function() {
var o = options;
var _this = $(this);
if( o.check === 'check' ) {
_this.attr('checked','checked');
}else if ( o.check === 'uncheck' ) {
_this.removeAttr('checked');
}
});
}
})(jQuery);和用户文档应该是您想要的:$('input').checkboxRadio({check:'check'});
https://stackoverflow.com/questions/14614484
复制相似问题