gpt4 book ai didi

javascript - actionEventListener ("click")在插入另一个项目后不起作用

转载 作者:行者123 更新时间:2023-12-02 23:34:42 26 4
gpt4 key购买 nike

我试图在 filtersSpace div 元素内动态添加 div 元素,同时为 div 元素内的每个按钮添加一个事件监听器,但是当我插入第二个元素时,第一个元素将被插入添加后不起作用。

有人可以帮我吗?

case "status":
filtersSpace.innerHTML +=
`<div class="card border-dark mx-2 my-3" style="width: 23%;">
<h5 class="card-header">Status</h5>
<div class="card-body">
<tr>
<select class="custom-select mr-sm-2" id="${'statusInput' + statusFilterCounter.toString(10)}">
<option selected value="Solved">Solved</option>
<option value="Open">Open</option>
<option value="Pending">Pending</option>
</select>
</tr>
<tr>
<button type="button" class="btn btn-dark my-2" style="width: 100%;"
id="${'statusActionButton' + statusFilterCounter.toString(10)}">
Filter
</button>
<button type="button" class="btn btn-outline-dark my-2" style="width: 100%;"
id="${'statusCancelButton' + statusFilterCounter.toString(10)}">
Cancel
</button>
</tr>
</div>
</div>`;
defineFilter(
"status",
document.getElementById("statusInput" + statusFilterCounter.toString(10)),
document.getElementById("statusActionButton" + statusFilterCounter.toString(10)),
document.getElementById("statusCancelButton" + statusFilterCounter.toString(10))
);
statusFilterCounter += 1;
statusLink.disabled = true;
break;

...

function defineFilter(filterType, input, actionButton, cancelButton) {
actionButton.addEventListener("click",
function () {
filters.push({filterType : filterType, value : input.value});
actionButton.disabled = true;
print();
getDataFromJSon();
}
);
cancelButton.addEventListener("click",
function () {
var quantity = this.id.charAt(this.id.length - 1);
var counter = 0;
for (var i = 0; i < filters.length; i++){
if(filters[i].filterType == filterType){
console.log(">>>");
if(counter == quantity){
filters.splice(i, 1);
print();
getDataFromJSon();
break;
}
counter += 1;
}
}
actionButton.disabled = false;
}
);}

最佳答案

对动态添加的元素使用事件委托(delegate)。

请参阅下面我们如何使用 e.target.matches([CSS Selector]) 来决定要做什么。

const newAdd = () => {
const div = document.createElement('div');
div.innerHTML = `<button class='btn'>Click Me</button>`;
document.querySelector('.container').appendChild(div);
}

document.addEventListener('click', (e) => {
if(e.target.matches('.btn')) {
console.log('I was clicked !!!');
}

if(e.target.matches('#add')) {
newAdd();
}
});
<div class="container"></div>
<button id="add">Add</button>

关于javascript - actionEventListener ("click")在插入另一个项目后不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56328733/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com