


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>

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

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

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

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig


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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver CS6
Visual web development tools

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