为了账号安全,请及时绑定邮箱和手机立即绑定

使用 JavaScript 函数将数据添加到来自 HTML 文档的字符串

使用 JavaScript 函数将数据添加到来自 HTML 文档的字符串

慕莱坞森 2023-12-04 16:37:12
我编写了一个名为 TypeWriter2 的对象,然后我想为其添加一个名为 type2() 的函数。然后,我使用名为 init2() 的函数调用 TypeWriter2 对象,该函数从 html 文档中查询一些数据并将其传递给 TypeWriter2 对象。init2()从html文档中查询的数据是:txtElement2 = 一个 div 元素,type2() 函数将使用它来显示一些数据。words2 = txtElement2 中要显示的单词,即“Hello,there...Yoo”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);}提前致谢!
查看完整描述

1 回答

?
翻翻过去那场雪

TA贡献2065条经验 获得超13个赞

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

尝试重现案例: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);


}


查看完整回答
反对 回复 2023-12-04
  • 1 回答
  • 0 关注
  • 38 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信