Javascript Event Listener on click not working as expected

前端 未结 5 457
感动是毒
感动是毒 2021-01-20 15:54

I\'m trying to create one event listener to handle all my \"clicks\" by putting it on the body and doing some event delegation. A simple example of what i\'m trying to do i

5条回答
  •  旧巷少年郎
    2021-01-20 16:56

    If you want all the LI's in your body to be clicked, you can check against the nodeName.

    Here is the fiddle: https://jsfiddle.net/swaprks/f3crax1q/

    Javascript:

    document.body.addEventListener('click', function(e){
         if(e.target.nodeName == "LI"){alert("hi")}
    })
    

提交回复
热议问题