$(this) 在 jQuery 顶层的含义

meaning of $(this) at the jQuery top level

我理解事件处理程序中 $(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" 方法

根级别的

this 指的是 window 对象。
https://jsfiddle.net/z20x9owq/

When Used inside a callback Jquery "$(this)" 引用当前 DOM 元素 但是当在回调之外使用时,$(this) 是一个数组,它在第 0 个索引上具有 Window 对象,与 Javascript "this" 关键字相同,它也是 Window 对象在函数外部使用时。 一个很好的例子是:

console.log($(this)===this); //return false
console.log($(this)[0]===this); //return true

希望对您有所帮助:)