$(this)在jQuery顶层的含义
我理解事件处理程序中$(this)在jQuery顶层的含义,jquery,html,dom,this,element,Jquery,Html,Dom,This,Element,我理解事件处理程序中$(this)的含义 $("div#d1").on("mouseover", function() { $(this).attr("id", "d2"); alert("id: " + $(this).attr("id")); }); 但是,当它用于jQuery代码的顶层时,这意味着什么 var tgt = $("h2#slider"); tgt.hide(); tgt.slideDown(2000); $(this).on("click", function()
$(this)
的含义
$("div#d1").on("mouseover", function() {
$(this).attr("id", "d2");
alert("id: " + $(this).attr("id"));
});
但是,当它用于jQuery代码的顶层时,这意味着什么
var tgt = $("h2#slider");
tgt.hide();
tgt.slideDown(2000);
$(this).on("click", function() {
tgt.slideUp();
});
“this”是一个html元素,没有“on”方法或任何jQuery方法。您必须使用$(this)将其转换为jquery元素,以便使用“on”方法
此
在根级别引用窗口对象。在回调中使用时
Jquery“$(this)”
引用当前DOM元素
但是当在回调外部使用时,$(this)
是一个数组,该数组的第0个索引上有窗口对象,与Javascript
“this”关键字相同,该关键字在函数外部使用时也是窗口对象。
一个很好的例子是:
console.log($(this)===this); //return false
console.log($(this)[0]===this); //return true
希望有帮助:)
根级别的此
将引用。将其包装在中会将其作为一个整体返回。相关文件链接。