setInterval未按预期工作

时间:2015-08-18 23:57:10

标签: javascript jquery

我有一个span元素。当它悬停时,我预计它会每1秒更改为hello1 -> hello2 -> hello3,但它不是那样工作,为什么?

i = 0;
$('div').on('mouseenter', function() {
    interval = setInterval(function() {
        $('div').html('<span>hello' + i +'</span>');
          i++;
    }, 1000)

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><span>hello</span></div>

3 个答案:

答案 0 :(得分:3)

您的i会在setInterval之外递增,这意味着它只会在mouseenter上递增。您还应该在每次mouseenter时清除间隔,以避免同时出现大量间隔

i = 1;
var interval;
$('div').on('mouseenter', function() {
  clearInterval(interval);
  interval = setInterval(function() {
    $('div').html('<span>hello' + i + '</span>');
    i++;
  }, 1000)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><span>hello</span>
</div>

https://jsfiddle.net/wt73c6bs/

或者,如果您希望代码仅在悬停时递增并在停止悬停时重置,请使用以下

i = 1;
var interval;
$('div').hover(function() {
    clearInterval(interval);
    interval = setInterval(function() {
      $('div').html('<span>hello' + i + '</span>');
      i++;
    }, 1000)
  },
  function() {
    clearInterval(interval);
    i = 1;
    $('div').html('<span>hello</span>');
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><span>hello</span>
</div>

https://jsfiddle.net/wt73c6bs/1/

答案 1 :(得分:0)

我认为你想使用 .append()而不是 .html()

i = 1;
var interval;
     $('div').on('mouseenter', function() {
    clearInterval(interval);
    interval = setInterval(function() {
    $('div').append('<span>hello' + i + '</span>');
    i++;
   }, 1000)
})


 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><span>hello</span>
</div>

答案 2 :(得分:0)

这是一个纯JavaScript的简单版本!

<html>
<head>
    <title>STACK OVERFLOW TESTS</title>
    <style>

    </style>
</head>
<body>
    <span>Hello 0</span>

    <script>
        var innerNumber = 0; // The number that will increments.

        var span = document.querySelector('span'); // Adding some reference to the element and event handlers.
        span.addEventListener('mouseover', setInterval(changeText, 1000));


        function changeText(){
            span.innerHTML = 'Hello ' + (innerNumber + 1); // Obtaining the content of the element and adding 1.
            innerNumber = innerNumber + 1;        
        }

    </script>
</body>
</html>