提问人:Skulklife 提问时间:11/17/2023 最后编辑:Skulklife 更新时间:11/17/2023 访问量:37
原生javascript:fetch()后如何跳过重新绑定事件监听器?[复制]
Native javascript: How to skip rebinding eventlisteners after fetch()? [duplicate]
问:
几个月前,我开始使用原生javascript。当我使用 fetch() 时,我必须重新绑定事件侦听器(单击、更改等)。我可以跳过它来缩短代码吗?
例如,我使用:document.getElementById(“click”, function)
并且我必须在每次ajax调用后重复它们。
更新:示例代码
document.addEventListener("DOMContentLoaded", function(){
document.getElementById("another_button").addEventListener("click", antoher_function);
document.getElementById("another_button2").addEventListener("click", antoher_function2);
document.getElementById("another_button3").addEventListener("click", antoher_function3);
//just a fetch call for example
fetch(url, {method: 'POST',
body: data
})
.then(respone => response.json())
.then(json => {
//HERE IS MY PROBLEM, I have to add another buttons event listeners, to work again
document.getElementById("another_button").addEventListener("click", antoher_function);
document.getElementById("another_button2").addEventListener("click", antoher_function2);
document.getElementById("another_button3").addEventListener("click", antoher_function3);
});
})
答:
0赞
Thomas
11/17/2023
#1
是:您可以向文档根目录添加一次事件侦听器。该事件将冒泡到根目录,您可以在其中检查实际目标是否是您想要的按钮之一。例如:
document.addEventListener("click", function(event) {
switch (event.target.id) {
case "another_button": another_function(); break;
case "another_button2": another_function2(); break;
case "another_button3": another_function3(); break;
}
});
您可能希望使用而不是标识按钮,以及一些数据属性来传递参数。不过,这取决于您的具体情况。class
id
评论
0赞
Skulklife
11/17/2023
感谢您的回复!!这个和js事件委托终于解决了我的问题!
评论