更新 html 按钮后 AddEVentListener 不工作
AddEVentListener not working after updated html button
<!-- Any html blocks -->
{% for n in loop %}
<div class="update">
<div>
<button type="button" class="update--btn">-</button>
</div>
</div>
{% endfor %}
let updateBtn = document.getElementsByClassName('update--btn');
[...updateBtn].forEach(e => {
e.addEventListener('click', clickBtn);
})
function clickBtn() {
const xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.onload = () => {
let cartUpdate = this.closest('.update');
cartUpdate.innerHTML ='';
let cartUpdateInner = document.createElement('div');
cartUpdateInner.innerHTML = '<button type="button" class="update--btn">+</button>'
cartUpdate.appendChild(cartUpdateInner);
}
xhr.send();
}
第一次加载页面时,一切正常。但是第二次点击按钮,更改后 HTML 不起作用。
PS。我需要更改 html,而不仅仅是文本
您可以将更新按钮代码放在类似
的函数中
function addevent(){
[...updateBtn].forEach(e => {
e.addEventListener('click', clickBtn);
})
}
然后在第一次加载页面时调用它
window.onload = addevent;
然后您需要在添加新按钮后重新分配此事件,以便您可以在 clickBtn 函数的末尾调用此事件
addevent()
<!-- Any html blocks -->
{% for n in loop %}
<div class="update">
<div>
<button type="button" class="update--btn">-</button>
</div>
</div>
{% endfor %}
let updateBtn = document.getElementsByClassName('update--btn');
[...updateBtn].forEach(e => {
e.addEventListener('click', clickBtn);
})
function clickBtn() {
const xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.onload = () => {
let cartUpdate = this.closest('.update');
cartUpdate.innerHTML ='';
let cartUpdateInner = document.createElement('div');
cartUpdateInner.innerHTML = '<button type="button" class="update--btn">+</button>'
cartUpdate.appendChild(cartUpdateInner);
}
xhr.send();
}
第一次加载页面时,一切正常。但是第二次点击按钮,更改后 HTML 不起作用。
PS。我需要更改 html,而不仅仅是文本
您可以将更新按钮代码放在类似
的函数中function addevent(){
[...updateBtn].forEach(e => {
e.addEventListener('click', clickBtn);
})
}
然后在第一次加载页面时调用它
window.onload = addevent;
然后您需要在添加新按钮后重新分配此事件,以便您可以在 clickBtn 函数的末尾调用此事件
addevent()