Javascript 在jQuery中使悬停重复动作

Javascript 在jQuery中使悬停重复动作,javascript,jquery,Javascript,Jquery,如何根据您在#test上停留的时间,让jQuery在#test中重复添加等等 例如,我如何在您悬停在#test上时,每秒追加一次等等?您可以像这样使用setInterval: $('#test').hover( function () { $(this).append('Blah'); } ); 使用setInterval() 我将所有代码都包含在一个匿名作用域函数中,这样就不会污染全局作用域,并且我缓存了一个对$(this)的引用,以避免每秒进行一次新的计算,在超时时间内,您可以使用

如何根据您在
#test
上停留的时间,让jQuery在
#test
中重复添加
等等


例如,我如何在您悬停在
#test
上时,每秒追加一次
等等?

您可以像这样使用
setInterval

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

我将所有代码都包含在一个匿名作用域函数中,这样就不会污染全局作用域,并且我缓存了一个对
$(this)
的引用,以避免每秒进行一次新的计算,在超时时间内,您可以使用执行此操作:

(function() {
   var intv;
   $('#test').hover(
     function () {
        var $this = $(this);
        intv = setInterval(function() {
          $this.append('Blah');
        }, 1000);
     },
     function() {
       clearInterval(intv);
     }
  );
}());
var追加//var来存储间隔
$('#test')。鼠标悬停(函数(){//
var$this=$(this);//存储上下文,即触发悬停的元素
appending=setInterval(function(){//在清除间隔之前,以下函数每秒执行一次
$this.append(“Blah

”);//将内容附加到上下文 },1000);/1000表示以毫秒为单位的重复时间 },mouseleave上的函数(){// clearInterval(追加);//在mouseleave上清除间隔 });
对于非运行间隔使用
false
有什么好处吗(可能有,我只是不知道)?没有。使用
var-myInterval也会是一样的。@m90不。。。就像初始化变量一样,你能演示一下吗?我似乎无法让它工作。@UserIsCorrupt已经有了。。。请参见答案底部的示例链接-请注意下面的
$that=$(this)
行和注释以解释它,并且
$(this)
在那里不起作用。。。。试穿一件衣服,你会发现(或者不会,视情况而定!!)
$('#test').hover(
 function () {
setInterval(function() {
  $(this).append('Blah');
},1000)
 }
);
(function() {
   var intv;
   $('#test').hover(
     function () {
        var $this = $(this);
        intv = setInterval(function() {
          $this.append('Blah');
        }, 1000);
     },
     function() {
       clearInterval(intv);
     }
  );
}());
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
});