Home > Web Front-end > JS Tutorial > How to Pass the Correct Variable Value to a Function When Using Event Listeners in Loops?

How to Pass the Correct Variable Value to a Function When Using Event Listeners in Loops?

DDD
Release: 2024-10-25 08:23:29
Original
971 people have browsed it

How to Pass the Correct Variable Value to a Function When Using Event Listeners in Loops?

How to Pass JS Variable Value to a Function

When iterating through arrays and adding event listeners to each element, the value of the loop counter variable may not be preserved as expected. Instead of capturing the current value, the listener uses the final value after the loop has terminated. To address this issue and pass the actual value (not the reference) to the function, consider the following approaches:

Modern Browsers:

Utilize the let or const keywords to declare block-scoped variables:

<code class="javascript">for (let i = 0; i < results.length; i++) {
  let marker = results[i];
  google.maps.event.addListener(marker, 'click', () => change_selection(i));
}</code>
Copy after login

Older Browsers:

Create a separate scope to preserve the variable's value by passing it as a parameter to a nested function:

<code class="javascript">for (var i = 0; i < results.length; i++) {
  (function (i) {
    marker = results[i];
    google.maps.event.addListener(marker, 'click', function() {
      change_selection(i);
    });
  })(i);
}</code>
Copy after login

By utilizing an anonymous function and passing the variable as an argument, you effectively pass its value to the function and create a closure. This ensures that each listener has access to the correct value at the time of creation.

The above is the detailed content of How to Pass the Correct Variable Value to a Function When Using Event Listeners in Loops?. 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