我知道$(this)
產生一個jQuery對象,但我經常看到(特別是在jQuery插件中)使用return this.whatever
什麼是一般規則?
感謝
我知道$(this)
產生一個jQuery對象,但我經常看到(特別是在jQuery插件中)使用return this.whatever
什麼是一般規則?
感謝
這取決於this
指的是什麼。
在事件處理程序函數this
中引用事件引發的HTML元素。要對元素執行jQuery操作,請使用$(this)
來包裝HTML元素。
this
插件方法的範圍指的是jQuery選擇對象本身。另外,在插件中,jQuery方法each
用於爲jQuery選擇中的每個元素執行一個函數。這通常是插件編寫提供新方法的方式:
jQuery.fn.alertClasses = function()
{
// "this" refers to the jQuery object, returned by $(...)
if(this[0] === undefined)
return this;
this.each(function() {
// "this" now refers to an HTML element in the jQuery object
alert(this.className)
});
// "this" refers to the jQuery object again
return this;
}
簡而言之,它都是關於方法的上下文。當您查看更改this
的值的方法時,jQuery文檔解釋了此概念。
使用$(this)
如果你需要訪問你的對象作爲jQuery對象。如果你指的是,你不需要爲jQuery的,只是用this
正如你指出你的對象的內部屬性:
$(本) - 返回jQuery對象
這一點 - - 返回DOM對象
this.whatever將返回DOM對象的屬性/功能
$(本).whatever將返回jQuery對象的屬性/功能
$(this)
將額外的JQuery「糖」添加到元素,然後返回它。所以規則就是,如果你想調用JQuery方法,你只需要使用$(this)
,並且它還沒有通過$(..)
。
使用$(this)
當jQuery爲您需要的功能提供更好的接口(這是DOM操作的大部分時間)。
我建議使用this
時,你必須(在沒有jQuery的等價物),或者在基本界面比較簡單,比如調用form.submit()
而非$('form').trigger('submit')
。
如果您想在'this'上使用JQuery功能,請使用$(this)
。
當您不想在'this'上使用JQuery功能時使用'this'。
$(this)
給你this
裹在jQuery中。 $($(this))
與$(this)
相同,因此在這種情況下額外呼叫$
是不必要的。
答案是這取決於情況。在很多插件中,你在jQuery對象上調用插件方法,這使得this
已經包裝在jQuery!
這裏不需要檢查「undefined」嗎?我會想象,each()已經知道如何處理空的「集合」。事實上,我認爲你可以做'return this.each(function(){...});'。 –
事實上,我打賭這不是必要的,但它是寫了多少插件(可能是某種「優化」),它是一個很好的說明性案例。 –