代码之家  ›  专栏  ›  技术社区  ›  Park JongBum

jquery顶层的$(this)的含义

  •  2
  • Park JongBum  · 技术社区  · 7 年前

    我理解 $(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(); 
    }); 
    
    3 回复  |  直到 7 年前
        1
  •  4
  •   AaronHolland    7 年前

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

        2
  •  0
  •   Dev Singh    7 年前

    在回调中使用时 Jquery "$(this)" 引用当前的dom元素 但在回调之外使用时, $(this) 是一个数组,该数组在第0个索引上具有窗口对象,与 Javascript “this”关键字,在函数外部使用时也是窗口对象。 一个很好的例子是:

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

    希望有帮助:)

        3
  •  -1
  •   codegames    7 年前

    “this”是一个HTML元素,没有“on”方法或任何jquery方法。为了使用“on”方法,您必须将它转换为jquery元素和$(this)。