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

如何根据您悬停多长时间Blah使jQuery 重复附加?#test#test

例如,我怎样才能Blah在你悬停的每一秒追加一次#test

4

4 回答 4

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
   }
);

这里的工作示例

于 2012-04-17T09:58:36.553 回答
2
(function() {
   var intv;
   $('#test').hover(
     function () {
        var $this = $(this);
        intv = setInterval(function() {
          $this.append('Blah');
        }, 1000);
     },
     function() {
       clearInterval(intv);
     }
  );
}());

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

于 2012-04-17T09:59:55.503 回答
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
});
于 2012-04-17T10:00:03.217 回答
0

使用 setInterval()

$('#test').hover(
 function () {
setInterval(function() {
  $(this).append('Blah');
},1000)
 }
);
于 2012-04-17T09:59:23.187 回答