如何向jQuery添加一个函数?

Mas*_*ask 60 jquery

定义新的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)

  • 更重要的是,该链接另一端的文章并不那么好. (4认同)
  • `this`指的是jQuery对象,在这种情况下,它的长度是1,因为选择器是一个唯一的ID.然后使用`this [0]`获取HTMLElement.然后用`$(this [0])`在jQuery中重新包装它.为什么? (4认同)
  • @AlexisWilke - 感谢您解释downvote,但是这不回答被问到的问题吗? (3认同)
  • 如果您希望能够继续链,这是错误的,您的功能需要返回此链接. (2认同)
  • @xr280xr 因为随着时间的推移,界面(如何添加新功能)可能会发生变化。当您升级到较新版本的 jQuery 时,它可能会破坏您的代码。 (2认同)

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)

  • 我认为第8行应该是`new $ .MyFunc($(this),options);` (2认同)

Mar*_*evy 18

jQuery的文档有一款插件开发,在那里我发现这个例子:

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)

你可以在那里看到文档