简体   繁体   中英

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?

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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