addEventListener Using a For Loop and Passing Values
When using a for loop to add event listeners to multiple objects, the last object often becomes The target for all listener relocations. This article will address this issue and provide a corrected code using closures:
Overview of the problem:
Trying to add event listeners to multiple objects using a loop, But ultimately all listeners target the same object (the last one).
Fixed code:
closure is a way to prevent this kind of problem. The modified code is as follows:
// 函数在点击时运行: function makeItHappen(elem, elem2) { var el = document.getElementById(elem); el.style.backgroundColor = "red"; var el2 = document.getElementById(elem2); el2.style.backgroundColor = "blue"; } // 自动加载函数以添加侦听器: var elem = document.getElementsByClassName("triggerClass"); for (var i = 0; i
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3