Adding an event listener to an element that doesn't exist yet in vanilla javascript

前端 未结 4 2321
我在风中等你
我在风中等你 2021-02-18 16:23

In JQuery I can do:

$(document).on(\"click\",\"a.someBtn\",function(e){
    console.log(\"hi\");
});

to add an event listener to an element th

4条回答
  •  孤独总比滥情好
    2021-02-18 17:06

    You can use event.target

    A reference to the object that dispatched the event.

    Code

    (function () {
        "use strict";
            document.getElementsByTagName('body')[0].addEventListener('click', function(e) {
            if (e.target.tagName == 'A' && e.target.classList.contains("someBtn")) {
              alert('Clicked');
            }
          }, false);
    })();
    

    (function() {
      "use strict";
      var a = document.createElement('a');
      a.textContent = 'Click Me';
      a.href = '#';
      document.body.appendChild(a);
    
      document.getElementsByTagName('body')[0].addEventListener('click', function(e) {
        if (e.target.tagName == 'A') {
          alert('Clicked');
        }
      }, false);
    })();

提交回复
热议问题