我正在尝试这个 JavaScript 代码
var txt = "", txtLen = 0, elem='';
var speed=90;
function write( obj ) {
txt = obj.str;
speed = obj.speed;
elem = obj.elem;
txtLen = txt.length;
setTimeout("loop()", 300);
}
var c=0;
function loop() {
if( c <= txtLen ){
document.getElementById(elem).innerHTML+=txt.charAt(c);
c++;
setTimeout("loop()", speed);
} else {
c=0;
}
}
但是在 html 中,当我调用 write 函数两次时,它只打印最后一个,就像这样-
<font id="o"></font><br>
<font id="oo"></font>
<script>
write({
elem:'o',
speed:90,
str:'Hello'
});
write({
elem:'oo',
speed:90,
str:'World'
});
</script>
谁能告诉我错误在哪里吗?
最佳答案
这应该有效
function loop(obj, c) {
if( c <= obj.str.length ){
document.getElementById(obj.elem).innerHTML += obj.str.charAt(c);
setTimeout(loop, obj.speed, obj,c+1);
}
}
function write( obj ) {
setTimeout( loop, 300, obj, 0);
}
setTimeout 函数可以选择将变量传递给回调函数
关于javascript - 为什么它打印最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42522166/