我想添加一個新的方法到jQuery,以便我可以做一些像$('#id').MyOwnFunc()
。我的困惑是從不同的網站和堆棧溢出,我可以看到我可以使用以下兩種方法之一:通過直接建立在fn
,也是一個方法在jQuery中添加方法的困惑
// #1
jQuery.fn.MyOwnFunc = function() {
var o = $(this[0]) // It's your element
return this; // This is needed so others can keep chaining off of this
};
// #2
jQuery.fn.extend({
MyOwnFunc: function() {
return this.each(function() {
this.checked = true;
});
},
});
因此,我們可以通過上面的方法都建立在jQuery的新方法使用fn.extend
所以我的困惑是:
- 我的理解錯了嗎?
- 如果否,兩者都可以使用,那麼當我們已經有選項1時,爲什麼我們有
fn.extend()
? - 哪個更好?
請好心解釋一下,因爲我已經瀏覽了很多網站,但不明白你爲什麼有兩種方法?