This question already has answers here:
How does the “this” keyword work?
                                
                                    (22个答案)
                                
                        
                                在11个月前关闭。
            
                    
我正在写一个小脚本,在鼠标悬停时添加类,在鼠标离开时删除类。删除必须延迟。

以下脚本仅是addClass,不适用于removeClass。我没有错...

$(".result").hover(
  function () {
    $(this).addClass("current");
  },
  function () {
    setTimeout( function () {
        $(this).removeClass("current");
    }, 800)
  }
);


相同的脚本,但是没有setTimeout,可以工作...

$(".result").hover(
  function () {
    $(this).addClass("current");
  },
  function () {
    $(this).removeClass("current");
  }
);


谁能帮我?

谢谢!

最佳答案

在setTimeout内部,this的上下文不同。在这种情况下,您可以使用箭头函数()(如示例二所示)或使用.bind将作用域绑定到当前上下文



$(".result").hover(
  function() {
    $(this).addClass("current");
  },
  function() {
    setTimeout(function() {
      $(this).removeClass("current");
    }.bind(this), 800)
  });

// with arrow function

$(".result2").hover(
  function() {
    $(this).addClass("current2");
  },
  function() {
    setTimeout(() => {
      $(this).removeClass("current2");
    }, 800)
  });

.current {
  color: red;
}

.current2 {
  color: green;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='result'> I am the result </div>

<div class='result2'> I am the result2 </div>

10-07 19:57
查看更多