Home  >  Article  >  Web Front-end  >  Why Do Event Listeners in a For Loop Target the Last Object?

Why Do Event Listeners in a For Loop Target the Last Object?

DDD
DDDOriginal
2024-11-11 13:06:02809browse

Why Do Event Listeners in a For Loop Target the Last Object?

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 solve this problem and provide a corrected code using closures:

Problem overview:

Trying to use a loop to add event listeners to multiple objects, But ultimately all listeners target the same object (the last one).

Correction code:

Closing is a way to prevent such problems. 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 < 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);
    }()); // 立即调用
}

The above is the detailed content of Why Do Event Listeners in a For Loop Target the Last Object?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn