Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
$(this)在jQuery顶层的含义_Jquery_Html_Dom_This_Element - Fatal编程技术网

$(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

希望有帮助:)

根级别的此
将引用。将其包装在中会将其作为一个整体返回。相关文件链接。