我基本上试图遍历array
个类并将事件侦听器附加到每个类。
我的JS只会将事件侦听器附加到数组中的最后一项。
我唯一的猜测是内部for
循环在外循环完成之前无法附加eventListeners。
var buttonClasses = ['apple', 'pear'];
var buttonClassElements = []
for (var i = 0; i < buttonClasses.length; i++) {
var buttonClass = buttonClasses[i];
buttonClassElements[i] = document.getElementsByClassName(buttonClass);
var currentElement = buttonClassElements[i];
// Now cycle through the elements with the current class and add event listeners
for (var j = 0; j < currentElement.length; j++) {
currentElement[j].addEventListener('click', function() {
console.log('Clicked ' + buttonClass);
});
}
}
&#13;
<div class="apple">The Apple</div>
<div class="pear">The Pear</div>
&#13;