2017-10-04 45 views
1

Wow ..获得关于'this'的真实信息是不是容易,因为谷歌基本上忽略了这个词。在嵌套函数中使用'this'

该代码使用缩略图中的信息打开数据库中的图像.. 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); 
    }); 

此外,如果你能解释一下为什么要使用$(这)是一个jQuery对象,而不是仅仅“这个”以及它们如何不同,那将是巨大的。在此先感谢〜!

回答

3

这有两个独立的方面。

  1. 获得正确的thissetTimeout回调

  2. 调用showModalthis

#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

+1

另外这个问题回答有助于整个问题OP正经历:HTTPS: //sackoverflow.com/questions/5889237/jquery-nested-this-references –

+1

Hooray!非常感谢你,我试着把它变成一个变量,然后用电话,但不是在一起。另外感谢您阅读关于'this'的额外阅读,它帮助我理解了为什么我的其他一些尝试也无法正常工作(特别是试图访问属性而不是在参考上执行函数) –

0

这也将工作,如果你可以改变你的showModel功能是这样的:

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

和定时器方法内部

$(this).showModal();