Three solutions for sub-functions accessing external variables in JavaScript

Three solutions for sub-functions accessing external variables in JavaScript

Preface

When we write web pages, we will definitely often encounter the following situation:

<body>
  
<div class="btns-wrapper"></div>
  
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var wrapper = $('.btns-wrapper');
for(var i = 0; i < 5; i++){
 var btn = $('<button>Button' + i + '</button>').appendTo(wrapper);
 btn.on('click', function(evt){
  console.log('Click the button: ' + i);
 });
}
</script>
  
</body>

The code is very simple, just create a few buttons on the page and define the button click events

But when we click the button, we find that the obtained serial number is always 5, which is the last value of i.

This is because the anonymous function used to define the click event refers to the same variable i.

Solution 1: Execute immediately

var wrapper = $('.btns-wrapper');
for(var i = 0; i < 5; i++){
 var btn = $('<button>Button' + i + '</button>').appendTo(wrapper);

 //Default method //btn.on('click', function(evt){
 // console.log('Click the button: ' + i);
 //});

 //Method 1: Execute immediately btn.on('click', (function(n){
  return function(evt){
   console.log('Click the button: ' + n);
  }
 })(i));

}

This approach is to create a separate anonymous function (closure) for each button directly when defining the event, and each function holds the correct i variable

Solution 2: Use jQuery event passing

var wrapper = $('.btns-wrapper');
for(var i = 0; i < 5; i++){
 var btn = $('<button>Button' + i + '</button>').appendTo(wrapper);

 //Default method //btn.on('click', function(evt){
 // console.log('Click the button: ' + i);
 //});

 //Method 2: Use JQuery event parameter btn.on('click', { i: i }, function(evt){
  console.log('Click the button: ' + evt.data.i);
 });

}

This method is much simpler. You can just use jQuery to pass the parameter body to the anonymous function.

Solution 3: Use the data attribute of DOM

var wrapper = $('.btns-wrapper');
for(var i = 0; i < 5; i++){
 var btn = $('<button>Button' + i + '</button>').appendTo(wrapper);

 //Default method //btn.on('click', function(evt){
 // console.log('Click the button: ' + i);
 //});

 //Method 3: Using DOM's data attribute btn.data('i', i);
 btn.on('click', function(evt){
  console.log('Click the button:' + $(this).data('i'));
 });

}

This method is also very simple, but its disadvantage is that it is not possible to use the data attribute to define structured data.

Summarize

On the whole, if it is a jQuery environment, using event parameters to transfer variables is the simplest, and structured data can be passed.

Otherwise, it can only be done through immediate execution (closure).

This is the end of this article about how sub-functions in JavaScript access external variables. For more information about how sub-functions in JavaScript access external variables, please search previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • An article teaches you JS function inheritance
  • What is the length of a function in js?
  • JavaScript Basics Series: Functions and Methods
  • Use of JavaScript sleep function
  • Exception handling of built-in functions json_encode and json_decode in php
  • How to make your JavaScript functions more elegant
  • Summary of 50+ Utility Functions in JavaScript
  • In-depth understanding of JavaScript callback functions
  • JavaScript functional programming basics

<<:  How to implement scheduled backup of MySQL database

>>:  The use of mysql unique key in query and related issues

Recommend

Vue implements div wheel zooming in and out

Implement div wheel zooming in and out in Vue pro...

Why can't I see the access interface for Docker Tomcat?

Question: Is the origin server unable to find a r...

JavaScript to achieve the idea of ​​​​snake game

The implementation idea of ​​the javascript game ...

Solution to the garbled problem of web pages when the encoding is set to utf-8

Recently, when I was writing web pages with PHP, I...

K3s Getting Started Guide - Detailed Tutorial on Running K3s in Docker

What is k3d? k3d is a small program for running a...

WeChat Mini Programs Achieve Seamless Scrolling

This article example shares the specific code for...

How to Dockerize a Python Django Application

Docker is an open source project that provides an...

22 Vue optimization tips (project practical)

Table of contents Code Optimization Using key in ...

Example code and method of storing arrays in mysql

In many cases, arrays are often used when writing...

Vue uses OSS to upload pictures or attachments

Use OSS to upload pictures or attachments in vue ...

Implementing carousel effects with JavaScript

This article shares the specific code for JavaScr...

MySQL index coverage example analysis

This article describes MySQL index coverage with ...

Detailed examples of float usage in HTML/CSS

1. Basic usage examples of float 1. Let's fir...