在 JavaScript 中检测动态创建的输入的 ID
Detect the id of a dynamically created input in JavaScript
我正在使用 JavaScript 创建联系人列表,并为 table 中的每个条目创建一个编辑按钮。
如何检测我点击的特定编辑按钮的 id
?
rows[id] = table.insertRow(addRow);
cell1[id] = rows[id].insertCell(0);
cell2[id] = rows[id].insertCell(1);
cell3[id] = rows[id].insertCell(2);
cell4[id] = rows[id].insertCell(3);
cell1[id].innerHTML = contact.name;
cell2[id].innerHTML = contact.email;
cell3[id].innerHTML = contact.phone;
editButtons[id] = document.createElement('input');
editButtons[id].classList.add("editButton");
editButtons[id].type = "image";
editButtons[id].src = "edit.png"
editButtons[id].id = id;
editButtons[id].addEventListener('click', updateInForm);
如果没有 minimal, reproducible example,很难为您提供所需的确切答案,但您可能正在寻找 event.target
.
看看 documentation for DOM invent handlers。
具体来说,this part:
When the event handler is specified as an HTML attribute, the
specified code is wrapped into a function with the following
parameters:
event — for all event handlers except onerror. event, source, lineno,
colno, and error for the onerror event handler. Note that the event
parameter actually contains the error message as a string.
事件对象将有一个 target
属性,其中包含触发事件的元素。
还有
When the event handler is invoked, the this keyword inside the handler
is set to the DOM element on which the handler is registered. For more
details, see the this keyword documentation.
我正在使用 JavaScript 创建联系人列表,并为 table 中的每个条目创建一个编辑按钮。
如何检测我点击的特定编辑按钮的 id
?
rows[id] = table.insertRow(addRow);
cell1[id] = rows[id].insertCell(0);
cell2[id] = rows[id].insertCell(1);
cell3[id] = rows[id].insertCell(2);
cell4[id] = rows[id].insertCell(3);
cell1[id].innerHTML = contact.name;
cell2[id].innerHTML = contact.email;
cell3[id].innerHTML = contact.phone;
editButtons[id] = document.createElement('input');
editButtons[id].classList.add("editButton");
editButtons[id].type = "image";
editButtons[id].src = "edit.png"
editButtons[id].id = id;
editButtons[id].addEventListener('click', updateInForm);
如果没有 minimal, reproducible example,很难为您提供所需的确切答案,但您可能正在寻找 event.target
.
看看 documentation for DOM invent handlers。
具体来说,this part:
When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters:
event — for all event handlers except onerror. event, source, lineno, colno, and error for the onerror event handler. Note that the event parameter actually contains the error message as a string.
事件对象将有一个 target
属性,其中包含触发事件的元素。
还有
When the event handler is invoked, the this keyword inside the handler is set to the DOM element on which the handler is registered. For more details, see the this keyword documentation.