如何向 jQuery 添加函数?

定义一个新的 jQuery成员函数成员函数最简单的方法是什么?

这样我就可以称之为:

$('#id').applyMyOwnFunc()
66455 次浏览

请参阅 Basil Goldman的「 在 jQuery 中定义自己的函数」 :

在这篇文章中,我想介绍一下 中定义自己的函数 JQuery 和使用它们。

根据上面链接的博客文章中的代码进行了修改:

jQuery.fn.yourFunctionName = function() {
// `this` is the jQuery Object on which the yourFunctionName method is called.
// `arguments` will contain any arguments passed to the yourFunctionName method.
var firstElement = this[0];


return this; // Needed for other methods to be able to chain off of yourFunctionName.
};

使用:

$(element).yourFunctionName();

JQuery 的 extend函数可以做到这一点

jQuery.fn.extend({
check: function() {
return this.each(function() { this.checked = true; });
},
uncheck: function() {
return this.each(function() { this.checked = false; });
}
});

您可以看到文档 那里

Jquery 文档有一个关于 插件创作,的章节,我在那里发现了这个例子:

jQuery.fn.debug = function() {
return this.each(function(){
alert(this);
});
};

那你可以这么说:

$("div p").debug();

这是我喜欢定义自己的插件的模式。

(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 } );

这是一个插件,以最简单的形式..。

jQuery.fn.myPlugin = function() {
// do something here
};

不过,您真的需要查阅文档:

Http://docs.jquery.com/plugins/authoring

/* 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);