How to add new methods to the jQuery object?

后端 未结 2 628
夕颜
夕颜 2020-12-29 07:17

Is there some way to add methods to jQuery\'s objects?

For example, I have jQuery object

a = $(\'div\')

I\'d like that every object

2条回答
  •  北海茫月
    2020-12-29 07:38

    You have to add your function to the $.fn namespace. Please note that inside the function, this will refer to the jQuery object, not a DOM object.

    $.fn.doSomething = function () {
        this.css('color', 'red');
    };
    
    $('#retk').doSomething();
    

    ​ jsFiddle Demo

    Please read about writing jQuery plugins for additional guidelines.

提交回复
热议问题