![](/img/trans.png)
[英]How to differentiate cloned elements in jQuery and add events to cloned elements
[英]How to add to all cloned elements an eventlistener?
我有这个模板:
<template id="a">
<div class="b">
<h1 class="placeholder1"></h1>
<div class="info hide">
<p class="p1"></p>
</div>
</div>
我正在克隆它:
fetch("json/countries.json").then(res => res.json()).then(list => show(list));
function show(list) {
list.forEach(function (list) {
const clone = template.cloneNode(true);
clone.querySelector(".placeholder1").textContent = list.country;
})}
我试图将事件侦听器添加到每个克隆的对象,但结果是它仅将其添加到第一个克隆的元素,而不是其余的元素。
clone.querySelector(".placeholder1").addEventListener('click', fx_button1);
function fx_button1(){
document.querySelector(".info").classList.toggle("hide");
}
querySelector
MDN仅选择从给定选择器中找到的第一个匹配项。 您需要使用querySelectorAll
MDN ,然后迭代结果。
var cloneSet = clone.querySelectorAll(".placeholder1");
for(var i = 0; i < cloneSet.length; i++){
cloneSet[i].addEventListener('click', fx_button1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.