How to add new methods to the jQuery object?

时光毁灭记忆、已成空白 提交于 2019-12-18 11:47:35

问题


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 which was assigned like that, would have particular method (doSomething()) so I could invoke it like

a = $('.foo')
a.doSomething()

b = $('.bar')
b.doSomething()

回答1:


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.




回答2:


add it like

$.fn.doSomething = function(data){
    // data is the argument passed to doSomething
    return this.each(function(){
       var elem = $(this);
       //perform operation on elem
       // like to change background color use
       elem.css('background-color','red');

    });
}


来源:https://stackoverflow.com/questions/10895199/how-to-add-new-methods-to-the-jquery-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!