我收到错误消息,因为出现了Uncought语法错误:我的js代码中已经声明了标识符“ i”

时间:2019-08-03 13:52:52

标签: javascript

我的代码中出现错误,但没有得到任何解决方案,因为它表示未捕获的语法错误:标识符“ i”已经声明

const words = ["addictive", "scalable", "awesome"];
let i = 0;
let timer;

function typingEffect() {
  let word = words[i].split("");
  var loopTyping = function() {
    if (word.length > 0) {
      document.getElementById('word').innerHTML += word.shift();
    } else {
      deletingEffect();
      return false;
    };
    timer = setTimeout(loopTyping, 500);
  };
  
  loopTyping();
};

function deletingEffect() {
  let word = words[i].split("");
  var loopDeleting = function() {
    if (word.length > 0) {
      word.pop();
      document.getElementById('word').innerHTML = word.join("");
    } else {
      if (words.length > (i + 1)) {
        i++;
      } else {
        i = 0;
      };
      typingEffect();
      return false;
    };
    timer = setTimeout(loopDeleting, 200);
  };
  loopDeleting();
};

typingEffect();
<div class="flex">
	<p class="header-sub-title" id="word"></p><p class="header-sub-title blink">|</p>
</div>

.blink {
  animation: blink 0.5s infinite;
}
@keyframes blink{
  to { opacity: .0; }
}
.flex {
    display: flex;
}

任何帮助将不胜感激,实际上我对Java脚本还很陌生

2 个答案:

答案 0 :(得分:1)

您的代码看起来不错,我认为您的脚本运行后您的dom正在加载,这就是为什么这种情况发生的原因,您可以尝试一件事,将脚本放到html的这个div之后,我认为它会为您工作

答案 1 :(得分:1)

如果您将命名空间添加到i的作用域中,这应使其保持隔离状态

var i=94;// not the same i, but you can pass it in

var MyNameSpace = (function(outeri) {
  console.log(outeri);
  const words = ["addictive", "scalable", "awesome"];
  let i = 0;
  let timer;

  function typingEffect() {
    let word = words[i].split("");
    var loopTyping = function() {
      if (word.length > 0) {
        document.getElementById('word').innerHTML += word.shift();
      } else {
        deletingEffect();
        return false;
      }
      timer = setTimeout(loopTyping, 500);
    };

    loopTyping();
  }

  function deletingEffect() {
    let word = words[i].split("");
    var loopDeleting = function() {
      if (word.length > 0) {
        word.pop();
        document.getElementById('word').innerHTML = word.join("");
      } else {
        if (words.length > (i + 1)) {
          i++;
        } else {
          i = 0;
        }
        typingEffect();
        return false;
      }
      timer = setTimeout(loopDeleting, 200);
    }
    loopDeleting();
  };
 // so we can call it
  return {
    typingEffect: typingEffect
  };
})(i);

MyNameSpace.typingEffect();
<div class="flex">
  <p class="header-sub-title" id="word"></p>
  <p class="header-sub-title blink">|</p>
</div>