首页 > 解决方案 > 为动画文本输出编写脚本的问题

问题描述

我不明白问题是什么,我正在编写一个脚本,它必须自己输出文本,就好像有人在打字一样,但我不断抛出同样的错误,不要告诉我什么可以在这种情况下完成,我将不胜感激。

错误是子字符串方法不起作用 Uncaught TypeError: Cannot read properties of undefined (reading 'substring')

let quoteArray = [];
let index = 0;
let textPosition = 0;
let flag = true;
let destination = document.querySelector('#typedtext');

window.addEventListener('load', typewriter);

function loadQuote() {
const url = "https://api.quotable.io/random";

fetch(url)

.then(response => {
    if(response.ok) {
        return response.json();
    } else {
        console.log(response.status);
    }
})

.then(data => {
    quoteArray[index] = data.content;
});

}

function typewriter(){
if(flag) {
    loadQuote();
    quoteArray[index] + ' ';
    flag = false;
}

destination.innerHTML = quoteArray[index].substring(0, textPosition); the error is here

if(textPosition++ != quoteArray[index].length){
    setTimeout('typewriter()', 100);
} else {
    quoteArray[index] = ' ';
    setTimeout('typewriter()', 3000);
    textPosition = 0;
    flag = true;
}

}

标签: javascript

解决方案


推荐阅读