$(document).on() in plain JavaScript?

前端 未结 1 752
忘了有多久
忘了有多久 2021-02-20 10:34

In jQuery there is .on() which can be used as:

$(document).on(\'click\', \'.foo\', function() { /* ... */ });

This listens for click events on

1条回答
  •  长发绾君心
    2021-02-20 11:01

    That called event delegation, in the pure javascript you could attach the click event to the parent element then on click check if the clicked element match the target you want to click and perform the action you want ,like the example below :

    document.getElementById("parent-item").addEventListener("click", function(e) {
          // e.target is the clicked element!
          // If it was an item with class 'foo'
          if(e.target && e.target.className == "foo") {
             console.log("foo "+e.target.innerText+" was clicked!");
        }
    });
    

    Hope this helps.

    document.getElementById("parent-item").innerHTML += "
  • Item 3
  • "; document.getElementById("parent-item").addEventListener("click", function(e) { if(e.target && e.target.className == "foo") { console.log("foo "+e.target.innerText+" was clicked!"); } });
    • Item 1
    • Item 2

    0 讨论(0)
提交回复
热议问题