我正在尝试使用JavaScript和/或jQuery将文本添加到div中,然后每隔10秒将文本更改为不同的文本 - 这有点像纯文本的幻灯片。这是我的代码:
<div id="textslide"><p></p></div>
<script>
var quotes = new Array();
quotes[0] = "quote1";
quotes[1] = "quote2";
quotes[2] = "quote3";
quotes[3] = "quote4";
quotes[4] = "quote5";
var counter = 0;
while (true) {
if (counter > 4) counter = 0;
document.getElementById('textslide').firstChild.innerHTML = quotes[counter];
counter++;
setTimeout( // not sure what to put here, 500); // Want to delay loop iteration
}
</script>
答案 0 :(得分:7)
HTML:
<div id="textslide"><p></p></div>
的JavaScript / jQuery的:
var quotes = [
"quote1",
"quote2",
"quote3",
"quote4",
"quote5",
];
var i = 0;
setInterval(function() {
$("#textslide").html(quotes[i]);
if (i == quotes.length) {
i = 0;
}
else {
i++;
}
}, 10 * 1000);
<强> Working demo here 强>
答案 1 :(得分:1)
这是一个简单的JS
的建议function loop() {
if (counter > 4) counter = 0;
document.getElementById('textslide').firstElementChild.innerHTML = quotes[counter];
counter++;
setTimeout(loop, 500);
}
loop();
演示here
如果您想使用 jQuery ,可以使用此功能:$('#textslide p:first').text(quotes[counter]);
演示here
答案 2 :(得分:0)
而不是使用:
setInterval(function () {
//do your work here
}, 10000);
答案 3 :(得分:0)
使用函数并在body onload上调用
<html>
<head>
<script>
var counter = 0;
function changeText()
{
var quotes = new Array();
quotes[0] = "quote1";
quotes[1] = "quote2";
quotes[2] = "quote3";
quotes[3] = "quote4";
quotes[4] = "quote5";
if (counter > 4)
{
counter = 0;
}
document.getElementById("textslide").innerHTML = quotes[counter];
setTimeout(function(){changeText()},10000);
counter ++;
}
</script>
</head>
<body onload="changeText();">
<p id="textslide"></p>
</body>
</html>