如何向jQuery添加功能?


68

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

这样我就可以这样称呼:

$('#id').applyMyOwnFunc()

Answers:


112

请参阅在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();

4
不仅如此,该链接另一端的文章也不是那么好。
mkoistinen 2013年

是的,没有。您实际上应该使用该extend()函数是安全的... RageZ给出了一个答案,该答案给出了我认为正确的答案。
亚历克西斯·威尔克2014年

4
this引用jQuery对象,在这种情况下,其长度为1,因为选择器是应该唯一的ID。然后,使用来获取HTMLElement this[0]。然后,您使用来将其重新包装在jQuery中$(this[0])。为什么?
雪人2015年

35

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

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

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


12

jQuery具有执行此extend功能的功能

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

您可以在那里查看文档



-1
/* 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);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.