【问题标题】:meaning of $(this) at the jQuery top leveljQuery 顶层 $(this) 的含义
【发布时间】:2019-01-06 06:16:45
【问题描述】:

我理解事件处理程序中$(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(); 
}); 

【问题讨论】:

标签: jquery html dom this element


【解决方案1】:

根级别的this指的是窗口对象。
https://jsfiddle.net/z20x9owq/

【讨论】:

    【解决方案2】:

    当在回调中使用时 Jquery "$(this)" 指的是当前的 DOM 元素 但是当在回调之外使用时,$(this) 是一个数组,其 Window 对象位于第 0 个索引上,与 Javascript "this" 关键字相同,在函数外使用时也是 Window 对象。 一个很好的例子是:

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

    希望对你有帮助:)

    【讨论】:

      【解决方案3】:

      "this" 是一个 html 元素,没有 "on" 方法或任何 jQuery 方法。您必须使用 $(this) 将其转换为 jquery 元素才能使用“on”方法

      【讨论】:

        猜你喜欢
        • 2012-04-04
        • 1970-01-01
        • 2010-11-03
        • 1970-01-01
        • 2013-01-08
        • 2010-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多