Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

259
Visualizações
Removing the item with onClick and eventListener

In the JS code, there is a part which prints some number of items, and next to each item there is an icon for removing the item next to it:

 <img src="images/remove.png"  class="remove" onClick="remove_item(${index})"> 

So, when the user clicked a bin the item next to it will be removed by the function below. The point is that items are need to be stored in an array called list. So item will be removed from list. The function render is for printing the items again.

function remove_item(index) {
  list.splice(index, 1);
  localStorage.setItem('list', JSON.stringify(list));
  render(list); 

The code which is up is working perfectly. However the issue is that the task is needed to be done by using eventListener. For that img part is edited like below.

<img src="images/remove.png"  class="remove" data-index="${index}">

And the part which will remove the item from list is like below.

let remove = document.querySelectorAll(".remove"); 
Array.from(remove).forEach((el) => {
el.addEventListener('click', function() { 
    let index = el.getAttribute('data-index');
    list.splice(index, 1);
    render(list);
    localStorage.setItem('list', JSON.stringify(list));
})});

The problem is that, code is working only when page is refreshed before each click to any icon. So after clicking the icon, I have to refresh and then click again for removing some other item. How I can fix that?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

When you re-render the list the elements are all replaced, which strips the event handlers. You should probably just remove the actual element:

el.addEventListener('click', function() { 
    let index = el.getAttribute('data-index');
    list.splice(index, 1);
    el.remove();
    localStorage.setItem('list', JSON.stringify(list));
})});

Either that or run the code again after render which attaches the event handlers. Whatever makes the most sense with how you're rendering.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda