Javascript jQuery中的无限each()循环?
我有几个单独的标题:Javascript jQuery中的无限each()循环?,javascript,jquery,Javascript,Jquery,我有几个单独的标题: <h3 class="ads">First</h3> <h3 class="ads">Second</h3> <h3 class="ads">Third</h3> 我希望能够手动设置每次更改之间的等待时间,所以解释也会很有帮助 这里有一个稍微不同的方法 这里有一个稍微不同的方法 您可以使用递归优雅地执行此操作 // configure the delay var delay = 1000;
<h3 class="ads">First</h3>
<h3 class="ads">Second</h3>
<h3 class="ads">Third</h3>
我希望能够手动设置每次更改之间的等待时间,所以解释也会很有帮助
这里有一个稍微不同的方法
这里有一个稍微不同的方法
您可以使用递归优雅地执行此操作
// configure the delay
var delay = 1000;
// save a pointer to the first element
var first = $('.ads').first();
// this function does the following
// a. color the current element red
// b. make all siblings black
// c. call itself with the next applicable element
function change(_elem) {
_elem.css('color','red').siblings().css('color', 'black');
setTimeout(function() {
change((_elem.next().length > 0) ? _elem.next() : first);
}, delay);
}
// start if off
change(first);
演示:您可以使用递归优雅地执行此操作
// configure the delay
var delay = 1000;
// save a pointer to the first element
var first = $('.ads').first();
// this function does the following
// a. color the current element red
// b. make all siblings black
// c. call itself with the next applicable element
function change(_elem) {
_elem.css('color','red').siblings().css('color', 'black');
setTimeout(function() {
change((_elem.next().length > 0) ? _elem.next() : first);
}, delay);
}
// start if off
change(first);
演示:使用
设置间隔
而不是设置超时
作为初学者。@d'alar'cop:呃,为什么?对不起,你不想让它继续运行吗?也许我误解了。没关系。先用setInterval
而不是setTimeout
。@d'alar'cop:呃,为什么?对不起,你不想让它继续运行吗?也许我误解了。没关系。$($headers.get(i))
我得到了。。。改用$headings.eq(i)
。对不起,这是什么语言?我已经更新了,因为这是一个很好的建议。但是“mein got”看起来不像英语。$($headers.get(i))
mein got。。。改用$headings.eq(i)
。对不起,这是什么语言?我已经更新了,因为这是一个很好的建议。但是“mein got”看起来不像英语。
// configure the delay
var delay = 1000;
// save a pointer to the first element
var first = $('.ads').first();
// this function does the following
// a. color the current element red
// b. make all siblings black
// c. call itself with the next applicable element
function change(_elem) {
_elem.css('color','red').siblings().css('color', 'black');
setTimeout(function() {
change((_elem.next().length > 0) ? _elem.next() : first);
}, delay);
}
// start if off
change(first);