Javascript / jQuery 或每隔几秒钟更改一次文本的东西
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6398526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript / jQuery or something to change text every some seconds
提问by Neil
Need JavaScript or jQuery something to change text every some seconds... with user doing anything.
需要 JavaScript 或 jQuery 的东西来改变文本每隔几秒钟......用户做任何事情。
Example:
例子:
"Welcome" changes to "Salmat datang" changes to "Namaste" etc after 3 secs and loops back.
“欢迎”更改为“Salmat datang”,3 秒后更改为“Namaste”等并循环返回。
回答by Thomas Shields
As others have said, setInterval
is your friend:
正如其他人所说,setInterval
你的朋友是:
var text = ["Welcome", "Hi", "Sup dude"];
var counter = 0;
var elem = document.getElementById("changeText");
var inst = setInterval(change, 1000);
function change() {
elem.innerHTML = text[counter];
counter++;
if (counter >= text.length) {
counter = 0;
// clearInterval(inst); // uncomment this if you want to stop refreshing after one cycle
}
}
<div id="changeText"></div>
回答by Darin Dimitrov
You may take a look at the setInterval
method. For example:
你可以看看setInterval
方法。例如:
window.setInterval(function() {
// this will execute on every 5 seconds
}, 5000);
回答by Ben
setInterval(function(){
alert('hello, do u have a beer ?');
}, 1000);
where 1000ms = 1sec;
其中 1000 毫秒 = 1 秒;
回答by James Allardice
You can use setInterval
to call a function repeatedly. In the function you can change the required text.
您可以使用setInterval
重复调用函数。在该功能中,您可以更改所需的文本。
The list of texts to change between could be stored in an array, and each time the function is called you can update a variable to contain the current index being used. The value can loop round to 0
when it reaches the end of the array.
要在它们之间切换的文本列表可以存储在一个数组中,每次调用该函数时,您都可以更新一个变量以包含正在使用的当前索引。该值可以循环到0
到达数组末尾时。
See this fiddlefor an example.
有关示例,请参阅此小提琴。