Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

182
Vistas
use fetch API and event handler

I loaded my local .json file with fetch, and I registered an event handler on a button element.

Here is my code:

        let tagName;
        function start(){
            fetch("./product.json")
            .then(response=>response.json())
            .then(data=>addItem(data,tagName))
            .catch(error=>console.log(error));            
        }
        start();
        
        function addItem(data,tagName){                
            var container = document.getElementById("itemBox");
            for(let i=0;i<data.length;i++){                       
                var div = document.createElement("div");
                var img = data[i].itemImg;                                  
                div.className = "imgBox";
                div.innerHTML = "<img src= "+img+">";
                container.appendChild(div);
            }
        };
        
        let tagBtn = document.getElementById("tagsubmit");
        tagBtn.onclick = function(){
            document.getElementById("tmp").innerHTML = "HELPME";
        }

When I opened this html file, json file is loaded&rendered succesfully, but the button with event handler doesn't work.

How can I make both of them work successfully?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Try to use the event delegation feature, like this:

document.getElementById('itemBox').addEventListener('click', (event) => {
    if (event.target.id === 'tagsubmit') {
        document.getElementById('tmp').innerHTML = 'HELPME';
    }
});

Nice tutorial by Dmitri Pavlutin: https://dmitripavlutin.com/javascript-event-delegation/

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda