JavaScript Event Listener for Clicks on Class
To attach a click event listener to a class, you can use the addEventListener() method. This method takes three arguments:
In your example, you are using the addEventListener() method correctly. However, there are two issues:
1. Element Selection Mistake
You are selecting the class elements using document.getElementsByClassName("classname"), which returns an HTMLCollection or a NodeList (depending on the browser). These are not arrays, so you cannot use the array bracket notation to directly attach an event listener to each class element.
2. Event Listener Function Error
In your event listener function, you are calling it when you attach it to the class elements. This means the function is immediately executed when the listener is added. Instead, you should pass in the function as a reference without calling it:
classname.addEventListener('click', myFunction, false);
Corrected Code
Here is the corrected code:
var elements = document.getElementsByClassName("classname"); var myFunction = function() { var attribute = this.getAttribute("data-myattribute"); alert(attribute); }; for (var i = 0; i < elements.length; i++) { elements[i].addEventListener('click', myFunction, false); }
This code will now correctly add an event listener to each class element and trigger the provided function when the element is clicked, displaying the element's data-myattribute attribute value in an alert.
The above is the detailed content of How to Properly Attach a Click Event Listener to Multiple Elements with the Same Class in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!