简体   繁体   English

为什么这个addEventListener对我创建的li元素不起作用?

[英]why this addEventListener not working for the li element I create?

I try to implement an aotocomplete input. 我尝试实现aotocomplete输入。 I want when user clicked new added li element, the input value will be the value of the li element. 我想当用户单击新添加的li元素时,输入值将是li元素的值。 However, this addEventListener seems not work in this function. 但是,此addEventListener似乎不适用于此功能。 May I know why? 我可以知道为什么吗? I think every new li element did create before I add event listener to them. 我认为在将事件侦听器添加到它们之前,确实会创建每个新的li元素。

function displayMatches(matchesArr) {
  var newLi;
  for (let j of matchesArr) {
    newLi = document.createElement('li');
    newLi.innerHTML = `<li id="${j.replace(/\s/g,'')}">${j}</li>`;
    autoResults.innerHTML += newLi.innerHTML;
    document.getElementById(j.replace(/\s/g, '')).addEventListener("click",
      function(e) {
        alert("Hello World!");
      })
  }
}

If I use NewLi it also doesn't work. 如果我使用NewLi,它也不起作用。

newLi.addEventListener("click", 
    function(e) {
        alert("Hello World!");
    })

The li that you're adding to the DOM is not the same one as newLi . 您要添加到DOM中的linewLi You're creating a brand new element when you assign to .innerHTML . 分配给.innerHTML时,您正在创建一个全新的元素。 You're also destroying and recreating all the old elements in autoResults . 您还将破坏并重新创建autoResults所有旧元素。 When you assign to .innerHTML it parses the HTML text from scratch, creating all new elements; 当您分配给.innerHTML它将从头开始解析HTML文本,从而创建所有新元素。 any properties that were set on the old elements, such as event listeners, are lost. 在旧元素上设置的所有属性(例如事件侦听器)都将丢失。

Instead of assigning to .innerHTML , append the element itself. 而不是分配给.innerHTML ,而是附加元素本身。

 function displayMatches(matchesArr) { var newLi; for (let j of matchesArr) { newLi = document.createElement('li'); newLi.id = j.replace(/\\s/g, ''); newLi.innerHTML = j; newLi.addEventListener("click", function(e) { alert("Hello World!"); }); autoResults.appendChild(newLi); } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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