在setTimeout内运行的函数丢失范围

时间:2014-12-11 23:01:50

标签: jquery scope settimeout

我无法正常启动以下功能。一切正常,除了我认为我从setTimeout函数中丢失了范围。 这是JS:

function galContent(){
    var hovInt;
    $(".element").each(function(){
        $(this).on("mouseenter", function(){
            clearTimeout(hovInt);
            hovInt = setTimeout(function(){
                //following line not working...
                $(this).find(".elContent").slideDown();
            }, 300);
       });
       $(this).on("mouseleave", function(){
           $(this).find(".elContent").slideUp(); 
       });
    });
}

HTML:

<div class="element web">
    <div class="elImg">
        <img src="01.jpg" alt="" title="">
    </div>
    <div class="elContent">

   </div>
</div>

1 个答案:

答案 0 :(得分:0)

如果this引用setTimeout中的另一个对象,则以这种方式传递引用:

function galContent(){
    var hovInt;
    $(".element").each(function(i){
        $(this).on("mouseenter", function(){
            clearTimeout(hovInt);
            hovInt = setTimeout(function(){
                //following line not working...
                $(".element").eq(i).find(".elContent").slideDown();
            }, 300);
       });
       $(this).on("mouseleave", function(){
           $(".element").eq(i).find(".elContent").slideUp(); 
       });
    });
}

属性index()也可以。

相关问题