原生 javascript:如何在 fetch() 之后跳过重新绑定事件监听器?

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

几个月前我开始使用原生 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);
});
})
javascript fetch bind
1个回答
0
投票

是的:您可以向文档根目录添加一次事件侦听器,然后检查目标是否确实是您想要的按钮之一。例如:

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
来标识按钮,也许还想使用一些数据属性来传递参数。但这取决于您的具体情况。

© www.soinside.com 2019 - 2024. All rights reserved.