Handling “onclick” event with pure JavaScript

后端 未结 3 644
旧时难觅i
旧时难觅i 2020-11-29 07:23

So this is really straight forward but I\'m still fairly new to JavaScript and just found JSFiddle. I\'m trying to find the element with the getElementById() t

3条回答
  •  时光取名叫无心
    2020-11-29 08:05

    Benjamin's answer covers quite everything. However you need a delegation model to handle events on elements that were added dynamically then

    document.addEventListener("click", function (e) {
        if (e.target.id == "abc") {
            alert("Clicked");
        }
    });
    

    For IE7/IE8

    document.attachEvent('onclick', function (e) {
        if (window.event.srcElement == "abc") {
            alert("Clicked");
        }
    });
    

提交回复
热议问题