javascript - 打字机功能
问题描述
有人可以解释为什么第一个代码块输出只是重复“T”但第二个代码块有效吗?第一个代码块:
function typeWriter() {
var i = 0,
txt = 'Testing',
speed = 40,
typed = document.getElementById('typewriter');
(function addChar() {
if (i < txt.length) {
typed.innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
})();
}
document.onload = typeWriter();
第二个代码块:
var i = 0,
txt = 'Testing',
speed = 40;
function typeWriter() {
if (i < txt.length) {
document.getElementById('typewriter').innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
解决方案
在第一个代码块中,每次调用 typeWriter() 都会设置 i=0,所以你总是得到 'T'。在第二个中,i 是在 typeWriter() 之外定义的,因此它的值在调用之间保持不变。
推荐阅读
- javascript - 以 UTC 存储日期 + 时区
- django - 纸元素导入在 python 中不起作用
- scala - 需要从我在我的 sbt 插件中使用的插件中提供一个 SettingKey
- javascript - Bootstrap 的 JavaScript 在创建反应项目时需要 jQuery
- r - 如何使用两个变量的值的组合创建一个可扩展的函数以将数据帧子集到数据帧列表中
- angularjs - 如何解决错误:$injector:unpr Unpr Unknown Provider in angularjs 同时连接 laravel 数据库
- c# - 特定环境中的间歇性 Bad Gateway 502 响应
- c++ - 在 main() 中使用 getline() 函数时出现命名空间错误
- embedded-linux - 是否可以从 u-boot 提示符将 uboot 命令的输出记录到文件中?
- jmeter - 如何在当前脚本中使用Include Controller调用.jmx生成的变量?