Home >Web Front-end >JS Tutorial >How to Assign Event Listeners to Multiple Objects Without Scope Conflicts?
Event Listener Assignment Using Iterative Functions
When using a loop to add event listeners to multiple objects, it may appear that all listeners reference the same object, typically the last one in the loop. This is because of how JavaScript handles variable scope and function closures.
To address this issue, employ the following approach:
// Autoloading function to add the listeners: var elem = document.getElementsByClassName("triggerClass"); for (var i = 0; i < elem.length; i += 2) { (function () { var k = i + 1; var boxa = elem[i].parentNode.id; var boxb = elem[k].parentNode.id; elem[i].addEventListener("click", function() { makeItHappen(boxa, boxb); }, false); elem[k].addEventListener("click", function() { makeItHappen(boxb, boxa); }, false); }()); }
In this code, an anonymous function is wrapped around the inner scope, creating a closure for each iteration. By executing the function immediately with the '()' operator, each iteration has its own private scope, ensuring that the variables and functions within don't interfere with those of other iterations.
This approach grants each event listener access to its intended variables, resolving the issue of all listeners targeting the same object.
The above is the detailed content of How to Assign Event Listeners to Multiple Objects Without Scope Conflicts?. For more information, please follow other related articles on the PHP Chinese website!