問題描述
有沒有辦法給 jQuery 的對(duì)象添加方法?
Is there some way to add methods to jQuery's objects?
例如,我有 jQuery 對(duì)象
For example, I have jQuery object
a = $('div')
我希望這樣分配的每個(gè)對(duì)象都有特定的方法 (doSomething()
),所以我可以像調(diào)用它一樣調(diào)用它
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()
推薦答案
你必須將你的函數(shù)添加到 $.fn
命名空間.請(qǐng)注意,在函數(shù)內(nèi)部,this
將引用 jQuery 對(duì)象,而不是 DOM 對(duì)象.
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 演示
請(qǐng)閱讀編寫jQuery插件以獲取更多指南.
Please read about writing jQuery plugins for additional guidelines.
這篇關(guān)于如何向 jQuery 對(duì)象添加新方法?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!