在jQuery中进行挥之不去的悬停重复操作

时间:2012-04-17 09:54:49

标签: javascript jquery

$('#test').hover(
 function () {
  $(this).append('Blah');
 }
);

如何根据您在Blah上空停留的时间,使jQuery在#test中反复追加#test

例如,我如何在Blah上空悬停{}} {}每天一次追加#test

4 个答案:

答案 0 :(得分:4)

您可以像这样使用setInterval

var myInterval = false;
$('#test').hover(
   function(){
      $that = $(this); 
      // need to save $(this) as 'this' will be different within setInterval
      myInterval = setInterval(function(){
         $that.append('Blah');
      }, 100); // repeat every 100 ms
   },function() {
      clearInterval(myInterval);  // clear the interval on hoverOut
   }
);

Working example here

答案 1 :(得分:2)

(function() {
   var intv;
   $('#test').hover(
     function () {
        var $this = $(this);
        intv = setInterval(function() {
          $this.append('Blah');
        }, 1000);
     },
     function() {
       clearInterval(intv);
     }
  );
}());

我已将所有代码都包含在一个匿名范围的函数中,以免污染全局范围,并且我缓存了对$(this)的引用,以避免在超时内每秒进行一次新的评估

答案 2 :(得分:2)

您可以使用 setInterval 执行此操作:

var appending; //var to store the interval

$('#test').hover(function(){ //on mouseenter
   var $this = $(this); //store the context, i.e. the element triggering the hover
   appending = setInterval(function(){ //the following function gets executed every second until the interval is cleared
      $this.append('<p>Blah</p>'); //append content to context
   },1000); //1000 meaning the repetition time in ms
},function(){ //on mouseleave
   clearInterval(appending); //clear the interval on mouseleave
});

答案 3 :(得分:0)

使用setInterval()

$('#test').hover(
 function () {
setInterval(function() {
  $(this).append('Blah');
},1000)
 }
);