javascript 定时数组
我错过了一些小事情..打印数组但不在行之间等待。
<script type="text/javascript">
function showLines()
{
arr =
[
"Hi!",
"Welcome!",
"Hello!"
]
var duration=2000;
document.getElementById("quotes").innerHTML=arr;
setTimeout('showLines()',duration);
}
</script>
I'm missing some little thing.. prints the array but doesn't wait in between lines.
<script type="text/javascript">
function showLines()
{
arr =
[
"Hi!",
"Welcome!",
"Hello!"
]
var duration=2000;
document.getElementById("quotes").innerHTML=arr;
setTimeout('showLines()',duration);
}
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
那是因为你只是打印出整个数组,试试这个。
那应该可以解决问题。
如果您一次只想要一个,则替换
为
That's because your just printing out the whole array, try this.
That should do the trick.
If you only want one at a time then replace
with
该行将
通过用逗号连接将
arr
转换为String
。因此,你会看到此函数是幂等,这可能不是您想要的。我认为您缺少的是一个索引,它可以让您知道下次执行该函数时您位于数组的哪个元素,并将
quotes
元素的内容替换为中的下一项数组。The line
will convert
arr
into aString
by joining it with commas. Therefore, you will seeThis function is idempotent, which is probably not what you are going for. I think what you're missing is an index that lets you know which element of the array you are on the next time the function is executed, and replaces the content of the
quotes
element with the next item in the array.这里的大多数答案都是在每次迭代时重新初始化数组。这样做是没有意义的。你应该这样做:
这样它就可以工作,你的数组和 i 只初始化一次。
编辑回应评论:
Most answers here are re initializing your array on each iteration.It makes no sense to do that. You should do it like this:
This way it works, and your array, and i are only initialized once.
EDIT In response to comment:
你从来没有要求他等待。您只是每 2 秒调用一次相同的函数。
尝试使用 showLines(i)、innerHTML += arr[i] 和 setTimeout(showLines,duration,i++)
You never asked him to wait. You're just calling the same function every 2 seconds.
Try with showLines(i), innerHTML += arr[i], and setTimeout(showLines,duration,i++)
首先,您应该将代码包装在
onload
或domready
函数中。 jQuery 擅长于此。您应该使用 window.onload = myfunc; 来执行此操作。您的代码应如下所示:
First of all, you should wrap your code in an
onload
ordomready
function. jQuery is good at this. You should usewindow.onload = myfunc;
to do this.Your code should look like this: