【问题标题】:Understanding scope and jquery chaining in javascript了解 javascript 中的作用域和 jquery 链接
【发布时间】:2018-05-02 13:50:04
【问题描述】:

我正在尝试更好地理解 javascript 中的范围和链接。我有以下效果很好

$("div.sked, div.report, div.database").hover (function (){
     let $this = $(this);
     let $pos = $this.position();
     $submenu = $this.find (":first-child");
     $submenu.css ('left', $pos.left + 30);
     $submenu.css ('top', $top);
     $submenu.show();
     })
     .mouseleave  (function (){
     $submenu.hide();
 });

但是当我在$submenu = $this.find (":first-child"); 之前添加一个let 然后$submenu 超出范围并且子菜单不会被隐藏。

我想了解编写此代码的正确方法。

谢谢...

【问题讨论】:

    标签: jquery scope chaining


    【解决方案1】:

    这是因为let 变量是块范围的,而不是函数范围的。如果你在第一个回调中声明了变量,你不能在另一个回调中使用它,因为块已经改变了。

    要在两个函数之间共享一个变量,您需要在一个使其对两个作用域都可用的地方声明它。

    但是,在您的情况下,没有这样的地方可以执行事件处理程序,而不管它们声明的顺序如何。因此,您需要在mouseleave 的回调中再次获取该元素。

    $("div.sked, div.report, div.database").hover(function() {
        let $this = $(this);
        let $pos = $this.position();
        $submenu = $this.find(":first-child");
        $submenu.css('left', $pos.left + 30);
        $submenu.css('top', $top);
        $submenu.show();
      })
      .mouseleave(function() {
        let $this = $(this);
        $submenu = $this.find(":first-child");
        $submenu.hide();
      });
    

    【讨论】:

      猜你喜欢
      • 2016-02-02
      • 2018-04-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-03
      • 2010-12-01
      • 1970-01-01
      • 2017-10-01
      相关资源
      最近更新 更多