当 lambda 函数引用封闭循环中的变量时的 javascript 范围问题 [英] javascript scope problem when lambda function refers to a variable in enclosing loop

查看:21
本文介绍了当 lambda 函数引用封闭循环中的变量时的 javascript 范围问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于 stackoverflow 的第一个问题 :) 希望我不会让自己难堪...

First question on stackoverflow :) Hope I won't embarrass myself...

我有一个 javascript 函数,可以加载专辑列表,然后为每个专辑创建一个列表项.列表项应该是可点击的,所以我调用 jQuery 的 click() 函数来做一些事情.我循环执行此操作.我的问题是所有项目似乎都获得相同的点击功能,即使我尝试制作一个在每次迭代中执行不同内容的新项目.另一种可能性是迭代变量以某种方式是全局的,并且函数引用了它.代码如下.debug() 只是 Firebug 的 console.debug() 的封装.

I have a javascript function that loads a list of albums and then it creates a list item for each album. The list item should be clickable, so I call jQuery's click() with a function that does stuff. I do this in a loop. My problem is that all items seem to get the same click function, even though I try to make a new one that does different stuff in each iteration. Another possibility is that the iteration variable is global somehow, and the function refers to it. Code below. debug() is just an encapsulation of Firebug's console.debug().

function processAlbumList(data, c) {
 for (var album in data) {
  var newAlbum = $('<li class="albumLoader">' + data[album].title + '</li>').clone();
  var clickAlbum = function() {
   debug("contents: " + album);
  };
  debug("Album: " + album + "/" + data[album].title);
  $('.albumlist').append(newAlbum);
  $(newAlbum).click(clickAlbum);
 }
}

这是上面函数运行时打印的内容的抄本,之后是我点击不同项目引起的一些调试行.它总是打印10",这是专辑变量采用的最后一个值(有 10 张专辑).

Here is a transcript of what it prints when the above function runs, after that are some debug lines caused by me clicking on different items. It always prints "10", which is the last value that the album variable takes (there are 10 albums).

Album: 0/Live on radio.electro-music.com
Album: 1/Doodles
Album: 2/Misc Stuff
Album: 3/Drawer Collection
Album: 4/Misc Electronic Stuff
Album: 5/Odds & Ends
Album: 6/Tumbler
Album: 7/Bakelit 32
Album: 8/Film
Album: 9/Bakelit
Album: 10/Slow Zoom/Atomic Heart
contents: 10
contents: 10
contents: 10
contents: 10
contents: 10

有什么想法吗?把我推上墙,这是.:)

Any ideas? Driving me up the wall, this is. :)

/斯蒂芬

推荐答案

你需要引入另一个作用域,比如这样:

You need to introduce another scope, such as like this:

var clickAlbum = (function (a) {
    return function () {
        debug("contents: " + a)
    };
})(album);

这篇关于当 lambda 函数引用封闭循环中的变量时的 javascript 范围问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆