如何向 jQuery 添加函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1768150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a function to jQuery?
提问by Mask
What's the easiest way to define a new jQuery member function?
定义新的 jQuery成员函数的最简单方法是什么?
So that I can call something like:
这样我就可以调用类似的东西:
$('#id').applyMyOwnFunc()
回答by keyboardP
Please see Defining your own functions in jQuery:
In this post, I want to present how easy define your own functions in jQuery and using them.
在这篇文章中,我想展示在 jQuery 中定义自己的函数并使用它们是多么容易。
From the post:
从帖子:
jQuery.fn.yourFunctionName = function() {
var o = $(this[0]) // This is the element
return this; // This is needed so other functions can keep chaining off of this
};
Just use:
只需使用:
$(element).yourFunctionName();
回答by tvanfosson
This is the pattern that I prefer to define my own plugins.
这是我更喜欢定义自己的插件的模式。
(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);
Applied as:
应用为:
$('selector').myfunc( { option: value } );
回答by Marcel Levy
The jquery documentationhas a section on plugin authoring,where I found this example:
jQuery.fn.debug = function() {
return this.each(function(){
alert(this);
});
};
Then you'd be able to call it this way:
那么你就可以这样称呼它:
$("div p").debug();
回答by RageZ
回答by JGarrido
Here's a plugin, in it's simplest form...
这是一个插件,它是最简单的形式......
jQuery.fn.myPlugin = function() {
// do something here
};
You'll really want to consult the documentation though:
不过,您确实想查阅文档:
回答by Amine_Dev
/* 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);