使用JavaScript函数将数据添加到来自HTML文档的字符串中,并在再次调用该函数后保留该数据

使用JavaScript函数将数据添加到来自HTML文档的字符串中,并在再次调用该函数后保留该数据,javascript,html,Javascript,Html,我编写了一个名为TypeWriter2的对象,然后我想给它添加一个名为type2的函数 然后,我使用名为init2的函数调用TypeWriter2对象,该函数从html文档中查询一些数据并将其传递给TypeWriter2对象 init2正在从html文档查询的数据是: txtElement2=一个div元素,type2函数将使用它来显示一些数据。 words2=将在txtElement2中显示的单词,即Hello,there。。。柳 wait2=稍后将传递给setTimeout的int。 typ

我编写了一个名为TypeWriter2的对象,然后我想给它添加一个名为type2的函数

然后,我使用名为init2的函数调用TypeWriter2对象,该函数从html文档中查询一些数据并将其传递给TypeWriter2对象

init2正在从html文档查询的数据是:

txtElement2=一个div元素,type2函数将使用它来显示一些数据。 words2=将在txtElement2中显示的单词,即Hello,there。。。柳 wait2=稍后将传递给setTimeout的int。 type2函数的意思是,每当txt2以3个连续点结束时,在开始处向txt2添加一个空字符串

问题是在将IIII添加到txt2和setTimeout=>this.type2、this.wait2之后;再次调用,IIII将从txt2中删除

document.addEventListener('DOMContentLoaded', init2);

const TypeWriter2 = function (txtElement2, words2, wait2 = 3000) {
    this.txtElement2 = txtElement2;
    this.words2 = words2;
    this.wait2 = parseInt(wait2, 10);
    this.txt2 = '';
    this.type2();
}

TypeWriter2.prototype.type2 = function () {
    this.txt2 = this.words2.substring(0, this.txt2.length + 1)

    if (this.txt2.substr(this.txt2.length - 3) === "...") {
        this.txt2 = this.txt2 + "iiiii"
        this.txtElement2.innerHTML = `<span class="intro-text">${this.txt2}</span>`;

    } else {
        this.txtElement2.innerHTML = `<span class="intro-text">${this.txt2}</span>`;
   }

    setTimeout(() => this.type2(), this.wait2);

}


function init2() {

    const txtElement2 = document.querySelector('.intro-text');
    const words2 = txtElement2.getAttribute('hello-txt');
    const wait2 = txtElement2.getAttribute("data2-wait");

    new TypeWriter2(txtElement2, words2, wait2);

}

提前谢谢

我无法使用发布的代码重现所述的错误,但如果将hello txt属性中的所有文本添加到txtElement2.innerHTML后,type2方法立即停止调用,则可以通过将else语句更改为else来解决问题

重犯未遂案:

你能试试这个吗.txtElement2.innerHTML+='
document.addEventListener('DOMContentLoaded', init2);

const TypeWriter2 = function (txtElement2, words2, wait2 = 3000) {
    this.txtElement2 = txtElement2;
    this.words2 = words2;
    this.wait2 = parseInt(wait2, 10);
    this.txt2 = '';
    this.type2();
}

TypeWriter2.prototype.type2 = function () {
  console.log('called');
    this.txt2 = this.words2.substring(0, this.txt2.length + 1)

    if (this.txt2.substr(this.txt2.length - 3) === "...") {
        this.txt2 = this.txt2 + "iiiii"
        this.txtElement2.innerHTML = `<span class="intro-text">${this.txt2}</span>`;
        console.log("finished")
    } else if(this.txt2.length <= this.words2.length){
        this.txtElement2.innerHTML = `<span class="intro-text">${this.txt2}</span>`;
        setTimeout(() => this.type2(), this.wait2);
    } else{
      console.log("finsished")
    }


}


function init2() {
    const txtElement2 = document.querySelector('.intro-text');
    const words2 = txtElement2.getAttribute('hello-txt');
    const wait2 = txtElement2.getAttribute("data2-wait");
    new TypeWriter2(txtElement2, words2, wait2);

}