[英]Why is the event listener added only to the first element?
So, after a button is clicked, there is this loop which goes through the array and creates a div containing data from each array element.因此,单击按钮后,会出现这个循环,它会遍历数组并创建一个包含每个数组元素数据的 div。 Now, after the divs are injected into DOM, I add an event listener to them, but only the firstly added element responds.
现在,在将 div 注入 DOM 之后,我向它们添加了一个事件侦听器,但只有第一个添加的元素会响应。 :/ The others are dead.
:/ 其他人都死了。 Any tips?
有小费吗?
btnLeft.addEventListener("click", function(){ let output = ""; for(let x of array){ output += `<div class="listItem" data-id="${x.id}"> <ul> <li>Name: ${x.name}</li> <li>Price: ${x.price}</li> </ul> </div>`; } leftList.innerHTML = output; document.querySelector(".listItem").addEventListener("click", function(){ console.log(this.getAttribute("data-id")); }); });
The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors.
Document 方法 querySelector() 返回文档中与指定选择器或选择器组匹配的第一个元素。 If no matches are found, null is returned.
如果未找到匹配项,则返回 null。
Since, document.querySelector(".listItem")
is only selecting the first element that matches the specified selector, the event listener is applied only to the first element.由于
document.querySelector(".listItem")
仅选择与指定选择器匹配的第一个元素,因此事件侦听器仅应用于第一个元素。
The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.
Document 方法 querySelectorAll() 返回一个 static(非实时)NodeList,表示与指定选择器组匹配的文档元素列表。
Try using document.querySelectorAll(".listItem")
and loop through this to add event listeners to all the elements.尝试使用
document.querySelectorAll(".listItem")
并循环遍历它以将事件侦听器添加到所有元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.