定义新jQuery 成员函数的最简单方法是什么?
所以我可以这样说:
$('#id').applyMyOwnFunc()
答案 0 :(得分:98)
请参阅Defining your own functions in jQuery:
在这篇文章中我想介绍一下 轻松定义自己的功能 jQuery并使用它们。
来自帖子:
jQuery.fn.yourfunctionname = function() {
var o = $(this[0]) // It's your element
return this; // This is needed so others can keep chaining off of this
};
用于:
$(element).yourfunctionname()
答案 1 :(得分:32)
这是我更喜欢定义自己的插件的模式。
(function($) {
$.fn.extend({
myfunc: function(options) {
options = $.extend( {}, $.MyFunc.defaults, options );
this.each(function() {
new $.MyFunc(this,options);
});
return this;
}
});
// ctl is the element, options is the set of defaults + user options
$.MyFunc = function( ctl, options ) {
...your function.
};
// option defaults
$.MyFunc.defaults = {
...hash of default settings...
};
})(jQuery);
应用为:
$('selector').myfunc( { option: value } );
答案 2 :(得分:18)
jquery documentation在plugin authoring,上有一个部分,我找到了这个例子:
jQuery.fn.debug = function() {
return this.each(function(){
alert(this);
});
};
然后你就可以这样称呼它:
$("div p").debug();
答案 3 :(得分:12)
jQuery具有extend
函数来执行该操作
jQuery.fn.extend({
check: function() {
return this.each(function() { this.checked = true; });
},
uncheck: function() {
return this.each(function() { this.checked = false; });
}
});
您可以看到文档there
答案 4 :(得分:4)
这是一个插件,最简单的形式......
jQuery.fn.myPlugin = function() {
// do something here
};
你真的想查阅文档:
答案 5 :(得分:-1)
/* This prototype example allows you to remove array from array */
Array.prototype.remove = function(x) {
var i;
for(i in this){
if(this[i].toString() == x.toString()){
this.splice(i,1)
}
}
}
----> Now we can use it like this :
var val=10;
myarray.remove(val);