Get li element onclick with pure javascript without applying onClick to each element

前端 未结 3 1573
醉梦人生
醉梦人生 2021-02-05 03:14

First of all I do not want to use jQuery, just pure javascript; please don\'t link to duplicate jQuery posts.

If I have a list like

3条回答
  •  离开以前
    2021-02-05 04:09

    You can use this:

    var link = document.getElementById("bulk");
    attachEvent(link, "click", EventHandler);
    
    function attachEvent(element, type, handler) {
        if (element.addEventListener) element.addEventListener(type, handler, false);
        else element.attachEvent("on"+type, handler);
    }
    
    function EventHandler(e) {
        console.log(e.target.id);
    }
    

    fiddle

    This work if li has children` elements:

    fiddle example with children

提交回复
热议问题