Home >Web Front-end >JS Tutorial >Why Doesn\'t `classname.addEventListener(\'click\', myFunction(), false);` Work for Adding Event Listeners to Classes?
In a quest to capture class attribute values upon clicks, you may have encountered an issue with your JavaScript code. Specifically, the line classname.addEventListener('click', myFunction(), false); fails to register event listeners on the elements.
To address this problem, let's analyze the code step by step:
Corrected Code:
To address the issue, we need to correctly attach event listeners to each element returned by getElementsByClassName. Here's 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); }
Explanation of Correction:
In ES6, the loop and event listener addition can be achieved more concisely:
Array.from(elements).forEach(function(element) { element.addEventListener('click', myFunction); });
For older browsers, like IE6-8, consider checking for the existence of getElementsByClassName before using it.
The above is the detailed content of Why Doesn\'t `classname.addEventListener(\'click\', myFunction(), false);` Work for Adding Event Listeners to Classes?. For more information, please follow other related articles on the PHP Chinese website!