Javascript 使用';这';在嵌套函数中

Javascript 使用';这';在嵌套函数中,javascript,jquery,function,this,Javascript,Jquery,Function,This,哇。。要获得关于“this”的真实信息并不容易,因为谷歌基本上忽略了这个词 代码使用缩略图中的信息从数据库中打开图像。。onlick可以工作,hover代码也可以工作,但是我不知道如何从mouseenter中获取“this”,以便在showmodel函数中使用 function showModal() { $("body").css("overflow-y", "hidden"); $(".small").removeClass("smallHov

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

代码使用缩略图中的信息从数据库中打开图像。。onlick可以工作,hover代码也可以工作,但是我不知道如何从mouseenter中获取“this”,以便在showmodel函数中使用

        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);
    });
函数showmodel(){
$(“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 srctextension=srclong.split(“.”);
$(“.big”).attr(“src”,srcshort[0]+'.+src扩展[1]);
}
$(“.small”)。单击(showModal);
无功定时器;
$(“.small”).mouseenter(函数(){
计时器=设置超时(函数(){

$(this).showmodel();//**这有两个不同的方面

  • setTimeout
    回调中获取正确的
    this

  • 用该
    this

  • #1由解决。您有几个选项,在本例中(目前)最简单的选项可能是使用变量:

    $(".small").mouseenter(function() {
        var _this = this; // ***
        timer = setTimeout(function(){
            $(_this).showModal(); // ***
        }, 2000);
    }).mouseleave(function() {
        clearTimeout(timer);
    });
    
    …但该代码仍然无法工作,因为
    showmodel
    不是jQuery对象的属性,它是一个独立的函数。要使用特定的
    this
    调用它,请使用:

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


    有关此
    的详细信息,以及。

    如果您可以像这样更改showModel功能,此功能也将起作用:

     $.fn.showModal = function() { 
            $("body").css("overflow-y", "hidden");
            $(".small").removeClass("smallHover");
            $(".modal").fadeIn(200);
            ... 
         }
    
    和内部定时器方法

     $(this).showModal();
    

    另外,这个问题的答案有助于解决OP遇到的整体问题:万岁!非常感谢,我尝试过将其作为一个变量,并使用call,但不是一起使用。还感谢对“this”的额外阅读,它帮助我理解了为什么我的其他尝试也不起作用(特别是尝试访问属性,而不是对引用执行函数)
     $(this).showModal();