JS event listener for a type of element?

前端 未结 5 1689
野趣味
野趣味 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:10

    I assume that you are looking for code along these lines:

    var paras = document.getElementsByTagName("p");
    
    // Loop through elements. 
    for(var i = 0; i < paras.length; i++) {
        // Add listener.
        paras[i].addEventListener("click",
            function() { 
                // Execute function.
            }, false);
    }
    

提交回复
热议问题