创建新的DOM(JavaScript)后如何解决事件问题?

当我单击项目时,它显示了clicked元素,但是在创建新项目后,它不适用于新项目。我们知道这很正常。

I know this is happening for the first items selector let items = document.querySelectorAll('.item');, it just holds the first element when page loads after creating new Items it does not affects the items selector. But I need to fix it. If I create new items it should work for all items (old and new both).

//for some stuff..
let

    items = document.querySelectorAll('.item');

items.forEach( (elm) =>{
  elm.addEventListener('click', ()=>{
      console.log(
        elm.innerText
      );
  })
});


//create new one
let

  btn = document.querySelector('button'),
  app = document.querySelector('.app-view'),
  dataId = 0;


btn.addEventListener('click', ()=>{
  dataId++;
  
  let 
    
    newItem = document.createElement('div');
  
  newItem.className = 'item';
  newItem.innerHTML = `I am from planet ${dataId}`;
  app.insertAdjacentElement ('beforeend', newItem);
  
});
.item{
  padding: .25rem 1rem;
  font-family: "Helvetica";
  color: purple;
  user-select:none;
  
}

.item:hover{
  cursor: default;
  border: 1px dotted #000;
}

.default-item{
  color: #007bff;
}

button{
  position: fixed;
  top: 1rem;
  right: 1rem;
  padding: .5rem 1rem;
}
<div class="app-view">
  <div class="item default-item">Default Item</div>
</div>

<button>
  Create New
</button>
评论
  • 微笑>失忆
    微笑>失忆 回复

    考虑使用事件委托:

    const itemContainer = document.querySelector('.app-view');
    
    item.addEventListener('click', e => {
      if (e.target.classList.contains('item') {
        // do stuff
      }
    });
    
  • 你太小
    你太小 回复

    An event listener needs to be attached to each newItem when it is created.

    我将其移至函数中,以便可以重复使用代码。

    //for some stuff..
    let items = document.querySelectorAll('.item');
    
    items.forEach((elm) => {
      bindClickEvent(elm); // Attach event to existing items
    });
    
    function bindClickEvent(elm) {
      elm.addEventListener('click', () => {
        console.log(
          elm.innerText
        );
      })
    }
    
    //create new one
    let btn = document.querySelector('button'),
        app = document.querySelector('.app-view'),
        dataId = 0;
    
    
    btn.addEventListener('click', () => {
      dataId++;
    
      let newItem = document.createElement('div');
    
      newItem.className = 'item';
      newItem.innerHTML = `I am from planet ${dataId}`;
      app.insertAdjacentElement('beforeend', newItem);
      
      bindClickEvent(newItem);  // Attach event to new item
    
    });
    .item {
      padding: .25rem 1rem;
      font-family: "Helvetica";
      color: purple;
      user-select: none;
    }
    
    .item:hover {
      cursor: default;
      border: 1px dotted #000;
    }
    
    .default-item {
      color: #007bff;
    }
    
    button {
      position: fixed;
      top: 1rem;
      right: 1rem;
      padding: .5rem 1rem;
    }
    <div class="app-view">
      <div class="item default-item">Default Item</div>
    </div>
    
    <button>
      Create New
    </button>