如何使用 setInterval() 更改文本?
我已经在这方面工作了一段时间了。我正在尝试创建一个简单的倒计时计时器。我已经让alert() 正常工作,但不幸的是textToChange 没有改变。我在下面复制了我的代码的副本。任何帮助将不胜感激!谢谢。
<script type="text/javascript">
var timeLeft = 0;
var changingTextElement;
var changingText = new Array();
var ctr = 0;
function timeMsg(thing)
{
var length = thing.inputbox.value*1000;
var t = setTimeout("alertMsg()",length);
timeLeft = length/1000;
initChangeText();
}
function alertMsg()
{
alert("Alert!");
}
function initChangeText(){
changingTextElement = document.getElementById("textToChange");
changingText[ctr] = changingTextElement.innerHTML;
ctr++;
while(timeLeft > 0){
changingText[ctr] = timeLeft;
timeLeft--;
ctr++;
}
ctr = 0;
setInterval("changingText()",1000);
}
function changingText() {
ctr++;
if(ctr >= changingText.length){
changingTextElement.innerHTML = 0;
}
else{
changingTextElement.innerHTML = changingText[ctr];
}
}
</script>
I've been working at this for quite some time now. I'm trying to create a simple timer that counts down. I've gotten the alert() to work, but unfortunately the textToChange does not change. I've reproduced a copy of my code below. Any help would be greatly appreciated! Thank you.
<script type="text/javascript">
var timeLeft = 0;
var changingTextElement;
var changingText = new Array();
var ctr = 0;
function timeMsg(thing)
{
var length = thing.inputbox.value*1000;
var t = setTimeout("alertMsg()",length);
timeLeft = length/1000;
initChangeText();
}
function alertMsg()
{
alert("Alert!");
}
function initChangeText(){
changingTextElement = document.getElementById("textToChange");
changingText[ctr] = changingTextElement.innerHTML;
ctr++;
while(timeLeft > 0){
changingText[ctr] = timeLeft;
timeLeft--;
ctr++;
}
ctr = 0;
setInterval("changingText()",1000);
}
function changingText() {
ctr++;
if(ctr >= changingText.length){
changingTextElement.innerHTML = 0;
}
else{
changingTextElement.innerHTML = changingText[ctr];
}
}
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在使用
changingText
函数和changingText
数组...看到冲突了吗?
作为附加信息,
请勿在
setInterval
方法中使用字符串作为名称函数。直接使用对该方法的引用You are using a
changingText
function and achangingText
array ...See the conflict ?
As additional info,
do not use strings as name functions in the
setInterval
method. Use a reference to the method directly对于一个简单的倒计时器来说,这段代码太大了。基本上,您应该做的是:
这可以很简单:
For a simple countdown timer, this code is too big. Basically, what you should be doing is:
setInterval
which decrements the counter and displays itThat can be simple as:
你的版本在小提琴中。我更改了函数名称
http://jsfiddle.net/mplungjan/jqeDv/
Your version in a fiddle. I changed the function name
http://jsfiddle.net/mplungjan/jqeDv/