【发布时间】:2022-01-07 18:40:14
【问题描述】:
我正在尝试将 HTML 数据动态插入到动态创建的表中,但是当我尝试为动态创建的按钮附加 addEventListner 时,事件不会触发。解决方案将不胜感激。
const put = document.querySelector(".puthere");
const v1 = document.querySelector(".v1");
const v2 = document.querySelector(".v2");
const create = document.querySelector(".create");
const updateDelete = document.querySelector(".update-delete");
const update = document.querySelectorAll(".active-update");
const dynamic = document.querySelector(".dynamic");
//FUNCTIONS
const operations = function (v1, v2) {
const html = ` <tr class = "update-delete">
<td> <input type="${v1}"></td>
<td ><input type="${v2}"></td>
<td> <button class = "active-update" data-set=".active-update"> UPDATE</button></td>
<td> <button > ❌ </button></td>
</tr>`;
put.insertAdjacentHTML("beforeend", html);
};
//CREATE TABLE COLUMNS
create.addEventListener("click", function (e) {
operations(v1.value, v2.value);
});
//Ataching eventlistner to parent element
updateDelete.addEventListener("click", function (e) {
if(e.target.classList.contains('active-update'){
console.log('click)})
});
<div >
<table class = "puthere">
<tr class="dynamic">
<th>BOOKS</th>
<th class = "books">PRICE</th>
<th > <button class="create" > CREATE</button> </th>
</tr>
<tr class = "update-delete dynamic">
<td><input type="text" class="v1"></td>
<td><input type="text" class="v2"></td>
<td> <button class = "active-update" data-set=".active-update"> UPDATE </button></td>
<td> <button > ❌ </button></td>
</tr>
</table>
</div>
【问题讨论】:
-
我之前也问过这个问题,得到了惊人的答案:stackoverflow.com/q/70454829/17716837
-
见What is DOM Event delegation? 和Event binding on dynamically created elements?。但是,您的代码中存在阻止其运行的语法错误 - 您应该先修复它们。
标签: javascript html