【问题标题】:Using 'this' in nested functions在嵌套函数中使用“this”
【发布时间】:2018-03-15 15:56:54
【问题描述】:

哇.. 要获得有关“this”的真实信息不容易,因为 google 基本上忽略了这个词。

代码使用缩略图中的信息打开数据库中的图像.. onlick 有效,悬停代码有效,但我不知道如何从 mouseenter 获取“this”以在 showModal 中使用功能。

        function showModal() {
        $("body").css("overflow-y", "hidden");
        $(".small").removeClass("smallHover");
        $(".modal").fadeIn(200);

        var altLong = $(this).attr("alt");
        var altSplit = altLong.split("#");
        $(".picTitle").text(altSplit[0]);                                           
        var srclong = $(this).attr("src");
        var srcshort = srclong.split("_");
        var srcextension = srclong.split(".");      
        $(".big").attr("src", srcshort[0]+'.'+srcextension[1]); 
    }
    $(".small").click(showModal);

    var timer;
    $(".small").mouseenter(function() {
        timer = setTimeout(function(){
            $(this).showModal(); // **<--this is the line that doesnt work**
        }, 2000);
    }).mouseleave(function() {
        clearTimeout(timer);
    });

如果你能解释为什么你会使用 $(this) 作为 jquery 对象而不是仅仅使用 'this' 以及它们有何不同,那就太好了。先谢谢了~!

【问题讨论】:

    标签: javascript jquery function this


    【解决方案1】:

    如果您可以像这样更改您的 showModel 函数,这也将起作用:

     $.fn.showModal = function() { 
            $("body").css("overflow-y", "hidden");
            $(".small").removeClass("smallHover");
            $(".modal").fadeIn(200);
            ... 
         }
    

    和内部定时器方法

     $(this).showModal();
    

    【讨论】:

      【解决方案2】:

      这有两个不同的方面。

      1. setTimeout 回调中获取正确的this

      2. 用那个this呼叫showModal

      #1 由this question's answers 寻址。您有多种选择,在这种情况下(目前)最简单的可能是使用变量:

      $(".small").mouseenter(function() {
          var _this = this; // ***
          timer = setTimeout(function(){
              $(_this).showModal(); // ***
          }, 2000);
      }).mouseleave(function() {
          clearTimeout(timer);
      });
      

      ...但是该代码仍然不起作用,因为showModal 不是 jQuery 对象的属性,它是一个独立的函数。要使用特定的 this 调用它,您可以使用 Function.prototype.call

      $(".small").mouseenter(function() {
          var _this = this;
          timer = setTimeout(function(){
              showModal.call(_this); // ***
          }, 2000);
      }).mouseleave(function() {
          clearTimeout(timer);
      });
      

      (或者,更改showModal 以接受元素作为参数,然后将其作为参数传递。)

      更多关于thisthis question's answers as well,以及this (old) post on my anemic little blog

      【讨论】:

      • 这个问题的答案也有助于解决 OP 遇到的整体问题:stackoverflow.com/questions/5889237/…
      • 万岁!非常感谢,我曾尝试将其设为变量,并使用调用,但不是一起使用。还要感谢您对“this”的额外阅读,它帮助我理解了为什么我的其他一些尝试也不起作用(特别是尝试访问属性而不是在引用上执行函数)
      猜你喜欢
      • 2014-01-10
      • 2018-10-22
      • 1970-01-01
      • 2012-03-27
      • 2015-11-18
      • 2019-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多