Home > Web Front-end > JS Tutorial > Why Do Event Handlers in JavaScript Loops Refer to the Same Variables?

Why Do Event Handlers in JavaScript Loops Refer to the Same Variables?

DDD
Release: 2024-11-05 20:36:02
Original
712 people have browsed it

Why Do Event Handlers in JavaScript Loops Refer to the Same Variables?

Working with Event Handlers in JavaScript Loops: Employing Closures for Distinct Event Handling

In JavaScript, when working with HTML code, event handlers play a crucial role in enabling user interactions with the web page. However, a common challenge arises when these event handlers are defined within a loop, leading to unexpected behavior.

To illustrate this issue, consider the following code snippet:

<code class="javascript">var blah = xmlres.getElementsByTagName('blah');
for(var i = 0; i < blah.length; i++) {
    var td = document.createElement('td');
    var select = document.createElement('select');
    select.setAttribute("...", "...");
    select.onchange = function() {
        onStatusChanged(select, callid, anotherid);
    };
    td.appendChild(select);
}
Copy after login

When an onchange event is triggered for a element that triggered the event. This behavior stems from the way JavaScript implements closures when defining event handlers.

Specifically, within the loop, the closure select.onchange = function() refers to the variables callid and anotherid, which carry the values assigned during the last iteration of the loop. Consequently, when an event is triggered, the values of these variables are not the ones associated with the specific element that triggers the event.

The above is the detailed content of Why Do Event Handlers in JavaScript Loops Refer to the Same Variables?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template