定义新的jQuery成员函数的最简单方法是什么?
这样我就可以这样称呼:
$('#id').applyMyOwnFunc()
Answers:
请参阅在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
};
只需使用:
$(element).yourFunctionName();
extend()函数是安全的... RageZ给出了一个答案,该答案给出了我认为正确的答案。
this引用jQuery对象,在这种情况下,其长度为1,因为选择器是应该唯一的ID。然后,使用来获取HTMLElement this[0]。然后,您使用来将其重新包装在jQuery中$(this[0])。为什么?
这是我喜欢定义自己的插件的模式。
(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 } );
new $.MyFunc($(this),options);
这是最简单形式的插件...
jQuery.fn.myPlugin = function() {
// do something here
};
不过,您确实要查阅文档: