簡體   English   中英

無法讀取 JavaScript 上未定義錯誤的屬性“長度”

[英]Cannot read property 'length' of undefined ERROR on JavaScript

我在 JavaScript 中創建了一個 Typewrite animation 但有一個問題,我的控制台每次重置時都會拋出下一個錯誤:Uncaught TypeError: Cannot read property 'length' of undefined at StartTextAnimation。 我希望你能幫助我在這里找到問題。 謝謝

<h1 class="typewrite fontrielsa" style="color: rgba(0,0,0,.5); font-weight: 300 !important; margin-bottom: 25px;"></h1>

<style>

.cursorType {
  border-right: .05em solid;
  animation: caret 1s steps(1) infinite;
}

@keyframes caret {
  50% {
    border-color: transparent;
  }
}


</style>

<script>

    document.addEventListener('DOMContentLoaded',function(event){
  // array with texts to type in typewriter
  var dataText = [ "MÁS DE 25 AÑOS DE EXPERIENCIA.", "EQUIPOS Y MATERIALES PARA LABORATORIO.", "DEPARTAMENTO DE INGENIERÍA.", "EMPRESA 100% MEXICANA."];

  // type one text in the typwriter
  // keeps calling itself until the text is finished
  function typeWriter(text, i, fnCallback) {
    // chekc if text isn't finished yet
    if (i < (text.length)) {
      // add next character to h1
     document.querySelector(".typewrite").innerHTML = text.substring(0, i+1) +'<span class="cursorType" aria-hidden="true"></span>';

      // wait for a while and call this function again for next character
      setTimeout(function() {
        typeWriter(text, i + 1, fnCallback)
      }, 100);
    }
    // text finished, call callback if there is a callback function
    else if (typeof fnCallback == 'function') {
      // call callback after timeout
      setTimeout(fnCallback, 5000);
    }
  }
  // start a typewriter animation for a text in the dataText array
   function StartTextAnimation(i) {
     if (typeof dataText[i] == 'undefined'){
        setTimeout(function() {
          StartTextAnimation(0);
        }, 1000);
     }
     // check if dataText[i] exists
    if (i < dataText[i].length) {
      // text exists! start typewriter animation
     typeWriter(dataText[i], 0, function(){
       // after callback (and whole text has been animated), start next text
       StartTextAnimation(i + 1);
     });
    }
  }
  // start the text animation
  StartTextAnimation(0);
});



</script>


無論未定義的檢查是通過還是失敗,都將運行dataText[i]檢查下的代碼部分。 您可以嘗試將其放入 if / else 中,例如:

function StartTextAnimation(i) {
  if (typeof dataText[i] == 'undefined'){
    // check if dataText[i] exists
    setTimeout(function() {
      StartTextAnimation(0);
    }, 1000);
  } else if (i < dataText[i].length) {
    // text exists! start typewriter animation
    typeWriter(dataText[i], 0, function(){
      // after callback (and whole text has been animated), start next text
      StartTextAnimation(i + 1);
    });
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM