gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 21:09:56 25 4
gpt4 key购买 nike

我编写了一个名为 TypeWriter2 的对象,然后我想为其添加一个名为 type2() 的函数。

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

init2()从html文档中查询的​​数据是:

  1. txtElement2 = 一个 div 元素,type2() 函数将使用它来显示一些数据。
  2. words2 = txtElement2 中要显示的单词,即“Hello,there...Yoo”
  3. wait2 = 稍后将传递给 setTimeout() 的 int。

type2() 函数的意思是,每当“txt2”以 3 个连续点结尾时,将“iiiiii”添加到“txt2”(开头为空字符串)。

问题在于,将“iiiiii”添加到“txt2”和“setTimeout(() => this.type2(), this.wait2);”之后再次调用,“iiiiii”将从“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);

}

提前致谢!

最佳答案

我无法使用发布的代码重现该错误,但很可能您可以通过将 else 语句更改为 else if 来解决该问题,例如一旦“hello-txt”属性中的所有文本都添加到 txtElement2.innerHTML

,type2 方法就会停止调用

尝试重现案例:https://jsbin.com/wovatit/1/edit?html,js,output

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);

}

关于javascript - 使用 JavaScript 函数将数据添加到来自 HTML 文档的字符串,并在再次调用该函数后保留该数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61125472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com