任何人都可以帮我这个吗? 我希望在之后的5秒内从console.log获取每个文本。 但这个代码控制台在前五秒后全部是li文本
<!doctype html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div class="phrase">
<ul class="items">
<li id="load">TEXT1</li>
<li id="load">TEXT2</li>
<li id="load">TEXT3</li>
</ul>
</div>
<script>
var phrases = [];
setTimeout(function(){
$('.phrase').each(function(){
var phrase;
$(this).find('li').each(function(){
// cache jquery object
var current = $(this);
phrase = current.text();
console.log(phrase);
});
});
}, 5000);
</script>
</body>
</html>
答案 0 :(得分:3)
我使用递归创建它:
(function myLoop(i, ctn) {
/// <summary>
/// find length of li elements and create a recursion
/// </summary>
/// <param name="i">length of li elements</param>
/// <param name="ctn">a counter</param>
setTimeout(function() {
$("body").append($(".items li").eq(ctn).text());
ctn++;
if (--i) myLoop(i, ctn); // decrement i and call myLoop again if i > 0
}, 1000)
})($(".items li").length, 0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="phrase">
<ul class="items">
<li class="load">TEXT1</li>
<li class="load">TEXT2</li>
<li class="load">TEXT3</li>
</ul>
</div>
答案 1 :(得分:2)
首先像Bala建议的那样,确保你的元素有唯一的ID。
您的JS代码可以更改为:
$(document).ready(function() {
var phrases = [];
var timeOut = 5000;
$('.phrase li').each(function(){
var current = $(this);
var phrase = current.text();
setTimeout(function(){
console.log(phrase);
}, timeOut);
timeOut += 5000;
});
});
每次获得新的li时都必须设置超时
Jsfiddle:http://jsfiddle.net/m6b87mg6/
答案 2 :(得分:1)
试
var next = $(".phrase").find('li:eq(0)');
var inter = setInterval(function () {
console.log( next.text());
next = next.next();
if(!next.length){
clearInterval(inter);
}
}, 5000);
<强> DEMO 强>
答案 3 :(得分:0)
这个怎么样
$('.phrase').each(function(){
var settimeout = 5000;
$(this).find('li').each(function(){
var phrase;
var current = $(this);
phrase = current.text();
setTimeout(function(){
console.log(phrase);
alert(phrase);
},settimeout );
settimeout = settimeout + 5000;
});
});
答案 4 :(得分:0)
这对我有用:
var phrases = [];
setTimeout(function(){
$('.phrase li').each(function(){
var phrase;
var current = $(this);
phrase = current.text();
console.log(phrase);
});
}, 5000);
工作jsbin:http://jsbin.com/tiyamo/1/
答案 5 :(得分:0)
setInterval(function(){
var text = [];
$("li.load").each(function(){
text.push($(this).text());
});
console.log(text.join(", "));
}, 1000);