首页 > 解决方案 > 打字机功能

问题描述

有人可以解释为什么第一个代码块输出只是重复“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);
  }
}

标签: javascript

解决方案


在第一个代码块中,每次调用 typeWriter() 都会设置 i=0,所以你总是得到 'T'。在第二个中,i 是在 typeWriter() 之外定义的,因此它的值在调用之间保持不变。


推荐阅读