2012-01-10 84 views
3

下面的代码将无法正常工作。我尝试了不同的变化&到处搜索,但没有运气。jQuery中的setTimeout()问题。每个

i = 1; 
var timer = new Array(); 
jQuery('a').each(function($) { 
    i++; 
    timer[i] = setTimeout(jQuery(this).remove(), i * 5000) 
}) 
+6

*下面的代码将无法正常工作。*你想做什么就做什么?我假设你的问题是你立即调用'jQuery(this).remove()'。 – 2012-01-10 01:15:11

+1

另请注意,传递给'each'的第一个参数实际上是所选元素集中DOM元素的索引。这意味着你不必维护一个单独的计数器。 [文档中的更多信息](http://api.jquery.com/each/)。 – 2012-01-10 01:43:32

回答

8

裹删除元素与功能

i = 1; 
var timer = new Array(); 
jQuery('a').each(function($) { 
    i++; 
    var thiz = jQuery(this); 
    timer[i] = setTimeout(function() { thiz.remove(); }, i * 5000); 
}) 
+0

完美,谢谢。 – 2012-01-10 01:27:55

-1

setTimeout接受JavaScript语句不是jQuery(this).remove()返回值:P 见this link

你可以function(){stuff},但不知道,当你希望它jQuery(this)将被处理。

0

尝试:

<html> 
<body> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> 
<a href="#">a</a> 
<a href="#">a</a> 
<a href="#">a</a> 
<a href="#">a</a> 
<a href="#">a</a> 
<a href="#">a</a> 
<script> 
i = 1; 
var timer = new Array(); 
    jQuery('a').each(function($) { 
    i++; 
    timer[i] = setTimeout(jQuery.proxy(function(){jQuery(this).remove();},this), i * 500); 
}) 
</script> 
</body> 
</html> 
3

菲利克斯已经暗示在评论这个问题,但我会扩大。

timer[i] = setTimeout(jQuery(this).remove(), i * 5000) 

你的问题就在于,你是调用jQuery(this).remove()并在此返回值传递给你的setTimeout。假设是你打算在超时过期时运行它。如果是这种情况,您需要将其封装在一个函数中,以便该函数将被传递给setTimeout并在计时器到期时执行。

var $el = jQuery(this); 

timer[i] = setTimeout(function(){ 
    $el.remove() 
}, i * 5000) 
4

的第一个参数setTimeout(或setInterval)需要一个函数的引用(或字符串,但你不希望使用字符串形式)。

不是将函数作为参数传递,而是调用函数并传递其结果。如果去掉括号,你会传递一个参考作用:

timer[i] = setTimeout(jQuery(this).remove, i * 5000) 

但随后你就会开始有与this是在功能实际运行时间错误的事情烦恼。尝试是这样的:

var i = 1, 
    timer = []; 
jQuery('a').each(function($) { 
    i++; 
    var $this = jQuery(this); 
    timer[i] = setTimeout(function() {$this.remove();}, i * 5000) 
}) 

这需要的方式关闭的优势工作在传递给setTimeout匿名函数将在其运行,即使在$this声明的功能的时间访问$this变量将在那时完成执行。

请注意,最好声明[]而不是new Array()

另请注意,您将i初始化为1,然后在使用它之前对其进行增量,以使您添加到阵列中的第一个元素将为timer[2]。您可能应该将其初始化为0,然后在设置每个计时器后递增。