日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Function in loop and closure

發布時間:2025/7/14 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Function in loop and closure 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

This article describe the famious issue “function in loop and closure” in JavaScript.

The root cause is loop statements (such as for, while) don’t have their own scope.

Let’s see an example first:

<ul><li>Item1</li><li>Item2</li><li>Item3</li></ul> var liNodes = document.getElementsByTagName("li");for (var i = 0; i < liNodes.length; i++) {liNodes[i].onclick = function() {alert("You click item " + i);};}

Now, if you click each of the list, all will produce a “You click item 3″ alert
box.

The number 3 comes out of the end execution of the loop (0, 1, 2 and out of the
loop i === 3).

Obviously, the result is not expected.

If you use JSLint to validate this piece of code, you will get the following warning:

Be careful when making functions within a loop. Consider putting the function in
a closure.

According to JSLint’s suggest, we have the first solution:

// GOOD - 0function clickNode(liNode, i) {liNode.onclick = function() {alert("You click item " + i);};} var liNodes = document.getElementsByTagName("li");for (var i = 0; i < liNodes.length; i++) {clickNode(liNodes[i], i);}

If you don’t want to create another function, consider using anonymous funtion:

// GOOD - 1var liNodes = document.getElementsByTagName("li");for (var i = 0; i < liNodes.length; i++) {(function(i) {liNodes[i].onclick = function() {// You click item 0// You click item 1// You click item 2alert("You click item " + i);};})(i);}

Notice: The self-executing function create a context scope which contains a local
variable i.

When the click event occurs, the variable i is coming from the closure which is
just the self-executing function scope.

There are many ways to solve this problem, following are another three ways:

// GOOD - 2var liNodes = document.getElementsByTagName("li");$.each(liNodes, function(i, item) {$(item).click(function() {// You click item 0// You click item 1// You click item 2alert("You click item " + i);});}); // GOOD - 3$("li").each(function(i, item) {$(item).click(function() {// You click item 0// You click item 1// You click item 2alert("You click item " + i);});}); // PREFERED - 4var liNodes = $("li").click(function(event) {var i = liNodes.index(this);// You click item 0// You click item 1// You click item 2alert("You click item " + i);});

轉載于:https://www.cnblogs.com/sanshi/archive/2009/06/30/1514065.html

總結

以上是生活随笔為你收集整理的Function in loop and closure的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。