本文介紹了如何向 jQuery 對象添加新方法?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
有沒有辦法給 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.
這篇關于如何向 jQuery 對象添加新方法?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!