如何向 jQuery 对象添加新方法?

2022-01-11 00:00:00 methods jquery jquery-plugins javascript

有没有办法给 jQuery 的对象添加方法?

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

例如,我有 jQuery 对象

For example, I have jQuery object

a = $('div')

我希望这样分配的每个对象都有特定的方法 (doSomething()),所以我可以像调用它一样调用它

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

推荐答案

你必须将你的函数添加到 $.fn 命名空间.请注意,在函数内部,this 将引用 jQuery 对象,而不是 DOM 对象.

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 演示

请阅读编写jQuery插件以获取更多指南.

Please read about writing jQuery plugins for additional guidelines.

相关文章