JS event listener for a type of element?

前端 未结 5 1694
野趣味
野趣味 2021-01-22 18:47

Is there a way to add some kind of listener for a type of html element? For example if i wanna call a function when the user clicks any p element

5条回答
  •  长情又很酷
    2021-01-22 19:09

    I'd just select all the elements on the page and add eventListeners on them like so:

    function addListeners(elementType, eventType, callback) {
        Array.prototype.slice.call(document.querySelectorAll(elementType)).forEach(function (el, i) {
            el.addEventListener(eventType, callback, false);
        });
    }
    

    Above we use querySelectorAll to pick all the wanted elements, convert it to an Array (if you use es6, you can use Array.from) and then we loop through the array and add listeners with the wanted callback.

    Here's an example: https://jsfiddle.net/a7en4d4s/

提交回复
热议问题