简体   繁体   English

如何向所有克隆的元素添加事件侦听器?

[英]How to add to all cloned elements an eventlistener?

I have this template: 我有这个模板:

<template id="a">
   <div class="b">
        <h1 class="placeholder1"></h1>
        <div class="info hide">
            <p class="p1"></p>
        </div>
    </div>

I am cloning it with: 我正在克隆它:

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;
})}

I am trying to add an event listener to each cloned object, but the result is that it only adds it to the first cloned element, not the rest. 我试图将事件侦听器添加到每个克隆的对象,但结果是它仅将其添加到第一个克隆的元素,而不是其余的元素。

clone.querySelector(".placeholder1").addEventListener('click', fx_button1);
function fx_button1(){
    document.querySelector(".info").classList.toggle("hide");
}

querySelector MDN only selects the first match found from the given selector. querySelector MDN仅选择从给定选择器中找到的第一个匹配项。 You need to use querySelectorAll MDN and then iterate the results. 您需要使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM