


JS FAQ: Why is the i that pops up when clicked always the last one_javascript tips
I saw many people asking this question in the front-end group, and someone asked this question again tonight, so I wrote an article to sort it out. First, take a look at the code. After clicking li, the index value corresponding to the current li will pop up. So many people wrote the following code.
var aLi = document.getElementsByTagName('li'); for(var i = 0; i < aLi.length; i++){ aLi[i].onclick = function(){ alert(i); } }
But the result is not satisfactory. For the sake of simplicity, we agree that there are 2 li in the page. After clicking li, all the pop-ups are 2.
Let’s first analyze why the result is 1. We can simply divide the loop into two parts.
i = 0时,aLi[0].onclick = function(){alert(i)} i = 1时,aLi[1].onclick = function(){alert(i)} i = 2时,不满足条件跳出循环.
When executing the click function, there will be a scope chain. This scope chain is a list of objects. This group of objects defines the variables in the code scope. (If you want to know more about the content of the variable object, you can view the variable object.) When we alert(i), we will look for the variable i from the inside to the outside. At this time, there are two objects in the scope chain of this function. At this time, the loop has ended, and the value of i at this time is 2. So when you click on any li, the pop-up will be 2, not the index value we want. The point is that what pops up is variable i, variable i, variable i. Say important things three times.
So here comes the question, how do we solve this problem. What we need to do is to save the value of i in the internal scope every time we bind an event to aLi[i]. The solution is as follows.
var aLi = document.getElementsByTagName('li'); for (var i = 0; i < aLi.length; i++) { (function(i){ aLi[i].onclick = function () { alert(i); }; })(i) }
This involves the concept of a block-level scope. Before ES6 came out, functions were the main means of creating block-level scopes. Here we put a layer of function outside aLi[i].onclick, using i as a parameter, and let's re-analyze the results.
i = 0时, (function(i){ aLi[0].onclick = function(){ alert(i); } })(0) i = 1时, (function(i){ aLi[1].onclick = function(){ alert(i); } })(1) i = 2时,不满足条件跳出循环.
Due to the additional layer of self-executing function wrapping, when we click li, there will be three levels of scope. From the inside to the outside, they are: the variable object inside the click function, the variable object of the self-executing function and the outermost scope. The layer's window object. When searching for the second level, i was found. The i of the self-executing function is equal to the passed parameter value, and the value of i at that time is correspondingly saved, so the corresponding index value pops up.
Let me share with you a common js problem. Clicking on li can pop up the current li index and innerHTML function
Clicking on one of them will result in the following alert:
According to our usual thinking, the code should be written like this:
var myul = document.getElementsByTagName("ul")[0]; var list = myul.getElementsByTagName("li"); function foo(){ for(var i = 0, len = list.length; i < len; i++){ list[i].onclick = function(){ alert(i + "----" + this.innerHTML); } } } foo();
But unfortunately, the result is like this:
Why is the index always 4? This is caused by the lack of block-level scope in js. Here are three solutions
1. Use closures
<script type="text/javascript"> var myul = document.getElementsByTagName("ul")[0]; var list = myul.getElementsByTagName("li"); function foo(){ for(var i = 0, len = list.length; i < len; i++){ var that = list[i]; list[i].onclick = (function(k){ var info = that.innerHTML; return function(){ alert(k + "----" + info); }; })(i); } } foo(); </script>
2. Use the new feature let in ES6 to declare variables
Variables declared with let will have block-level scope, which obviously meets the requirements. However, it should be noted that you need to add 'use strict' (use strict mode) for it to take effect
<script type="text/javascript"> var myul = document.getElementsByTagName("ul")[0]; var list = myul.getElementsByTagName("li"); function foo(){'use strict' for(let i = 0, len = list.length; i < len; i++){ list[i].onclick = function(){ alert(i + "----" + this.innerHTML); } } } foo(); </script>
3. Introduce jquery and use on or delegate for event binding (they all have the characteristics of event proxy)
<script type="text/javascript" src="jquery-1.8.2.min.js"></script> <script type="text/javascript"> $("ul").delegate("li", "click", function(){ var index = $(this).index(); var info = $(this).html(); alert(index + "----" + info); }); </script> <script type="text/javascript"> $("ul").on("click", "li", function(){ var index = $(this).index(); var info = $(this).html(); alert(index + "----" + info); }); </script>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

This article will guide you to create a simple picture carousel using the jQuery library. We will use the bxSlider library, which is built on jQuery and provides many configuration options to set up the carousel. Nowadays, picture carousel has become a must-have feature on the website - one picture is better than a thousand words! After deciding to use the picture carousel, the next question is how to create it. First, you need to collect high-quality, high-resolution pictures. Next, you need to create a picture carousel using HTML and some JavaScript code. There are many libraries on the web that can help you create carousels in different ways. We will use the open source bxSlider library. The bxSlider library supports responsive design, so the carousel built with this library can be adapted to any

Bring matrix movie effects to your page! This is a cool jQuery plugin based on the famous movie "The Matrix". The plugin simulates the classic green character effects in the movie, and just select a picture and the plugin will convert it into a matrix-style picture filled with numeric characters. Come and try it, it's very interesting! How it works The plugin loads the image onto the canvas and reads the pixel and color values: data = ctx.getImageData(x, y, settings.grainSize, settings.grainSize).data The plugin cleverly reads the rectangular area of the picture and uses jQuery to calculate the average color of each area. Then, use

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.
