代码之家  ›  专栏  ›  技术社区  ›  gareth power

Javascript EventListener在创建另一个时消失

  •  0
  • gareth power  · 技术社区  · 7 年前

    我试图创建一个脚本,其中一个select HTML对象检测到一个更改,获取其值,并创建另一个基于其值显示的标记。E、 g.用户选择“United Kingdom”和一个显示在div中的标签。这是可行的,但我有一个X按钮,它可以在单击时删除标签,使用 EventListener . 问题是,我只能删除创建的最后一个标记,因为用于创建每个标记的id的变量发生了变化,因此,只有最后一个有效。部分代码如下:

     document.getElementById("locations-editor-container1").innerHTML = 
        document.getElementById("locations-editor-container1").innerHTML+"<div 
        class='locations-editor-country-disp' id='"+country+"[@]'>"+country+"<svg  
       id='"+country+"[##]' class='locations-editor-x-button' 
       style='width:2vh;position:absolute;right:0.5vw;vertical-align:middle;' 
       viewBox='0 0 24 24'><path fill='#FFFFFF' 
    
    
          d='M19,6.41L17.59,5L12,10.59L6.41,
          5L5,6.41L10.59, 12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z'/></svg></div><br>";
                var countryId=country+"[##]";
                
         document.getElementById(countryId).addEventListener("click",function(){ remove(countryId)},false);
    
    1 回复  |  直到 4 年前
        1
  •  1
  •   HMR    7 年前

    下面是您的错误再现,因为您正在替换某些内容的innerHTML,您正在删除您正在替换的元素的事件侦听器。这就是为什么只有最后一个元素有效:

    const content = document.querySelector("#content");
    var counter = 0;
    const add = e => {
      content.innerHTML = 
          //you are replacing content, thus removing the event listeners of 
          //  previous elements
          content.innerHTML +
        `<div style="cursor: pointer;" id="div${++counter}">
            click me ${counter}
        </div>`;
      document.querySelector(`#div${counter}`)
      .addEventListener(
        "click"
        ,(x=>e=>{
          alert(`Counter for this div:${x}`);
        })(counter)
      );
    }
    document.querySelector("#myButton").addEventListener(
      "click"
      ,add
    );
    <div id="content">
    </div>
    <input type="button" id="myButton" value="add">

        const content = document.querySelector("#content");
        var counter = 0;
        const add = e => {
          //create a div (will not be added to dom yet)
          const div = document.createElement("div");
          div.innerHTML = 
            `<div style="cursor: pointer;" id="div${++counter}">
              click me ${counter}
            </div>`;
          div
          .addEventListener(
            "click"
            ,(x=>e=>{
              alert(`Counter for this div:${x}`);
            })(counter)
          );
          //add element to dom (do not replace content)
          content.appendChild(div);
        }
        document.querySelector("#myButton").addEventListener(
          "click"
          ,add
        );
        <div id="content">
        </div>
        <input type="button" id="myButton" value="add">