定义新的jQuery 成员函数最简单的方法是什么?
所以我可以这样称呼:
$('#id').applyMyOwnFunc()
Run Code Online (Sandbox Code Playgroud)
key*_*rdP 101
请参阅在jQuery中定义自己的函数:
在这篇文章中,我想介绍如何在jQuery中轻松定义自己的函数并使用它们.
从帖子:
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
};
Run Code Online (Sandbox Code Playgroud)
用过的:
$(element).yourFunctionName();
Run Code Online (Sandbox Code Playgroud)
tva*_*son 33
这是我更喜欢定义自己的插件的模式.
(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);
Run Code Online (Sandbox Code Playgroud)
应用为:
$('selector').myfunc( { option: value } );
Run Code Online (Sandbox Code Playgroud)
Mar*_*evy 18
jQuery.fn.debug = function() {
return this.each(function(){
alert(this);
});
};
Run Code Online (Sandbox Code Playgroud)
然后你就可以这样称呼它:
$("div p").debug();
Run Code Online (Sandbox Code Playgroud)
Rag*_*geZ 12
jQuery具有extend
这样做的功能
jQuery.fn.extend({
check: function() {
return this.each(function() { this.checked = true; });
},
uncheck: function() {
return this.each(function() { this.checked = false; });
}
});
Run Code Online (Sandbox Code Playgroud)
你可以在那里看到文档