用打字稿编写的CLick事件侦听器自行解除绑定

问题描述 投票:0回答:1

是Typescript的新手,但是对JavaScript有一定的经验。无法弄清楚为什么会这样。将事件侦听器附加到按钮,例如

document.querySelector("#sr").addEventListener("click", function () {
        console.log(1);
        new GetApi().entered_name();
    });

第一次可以正常运行,但之后不能正常运行。但是,当我删除new GetApi().entered_name()时,它总是可以正常工作。

这里是功能

entered_name()
     {
       console.log(document.getElementById("fname").value);
        return fetch("https://localhost:5001/api?search="+document.getElementById("fname").value)
            .then(Response=>Response.json())
            .then(data=>{
         console.log(data[0]);
         let res =new UserData(data[0]);
         console.log(res);
         let obj = new Display1();
         obj.showUserData(res);  


       }).catch(err=>console.log(err));
     }

这里是showUserData()

export class Display1
{
    showUserData(obj : UserData){
    {
        document.body.innerHTML += "Props in HTML tags";
    }
}
}

javascript typescript dom
1个回答
0
投票

您的showUserData方法通过将字符串添加到内部html中来重置DOM。因此,在该操作之后,将按字面意义重新创建元素#sr,并且应再次为其绑定所有事件。尝试使用insertAdjacentHTML。像这样的东西:

document.body.insertAdjacentHTML('beforeend', "Props in HTML tags");
© www.soinside.com 2019 - 2024. All rights reserved.