如何在JavaScript中复制变量? [英] How to copy a variable in JavaScript?

查看:125
本文介绍了如何在JavaScript中复制变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个JavaScript代码:

I have this JavaScript code:

for (var idx in data) {
    var row = $("<tr></tr>");
    row.click(function() { alert(idx); });
    table.append(row);
}

所以我通过一个数组,动态创建行我创建的单元格被忽略,因为它不重要)。重要的是我创建了一个包含idx变量的新函数。

So I'm looking through an array, dynamically creating rows (the part where I create the cells is omitted as it's not important). Important is that I create a new function which encloses the idx variable.

但是,idx只是一个引用,因此在循环结束时,

However, idx is only a reference, so at the end of the loop, all rows have the same function and all alert the same value.

我现在解决这个问题的方法之一是:

One way I solve this at the moment is by doing this:

function GetRowClickFunction(idx){
    return function() { alert(idx); }
}

,在调用代码中我调用

row.click(GetRowClickFunction(idx));

这可以工作,但有点丑陋。我想知道是否有更好的方法来复制当前值的idx在循环中?

This works, but is somewhat ugly. I wonder if there is a better way to just copy the current value of idx inside the loop?

虽然问题本身不是jQuery具体的(它涉及到JavaScript闭包/范围),我使用jQuery,因此一个jQuery-only解决方案是好的,如果它的工作。

While the problem itself is not jQuery specific (it's related to JavaScript closures/scope), I use jQuery and hence a jQuery-only solution is okay if it works.

推荐答案

您的循环:

for (var idx in data) {
  (function(idx) {
    var row = $("<tr></tr>");
    row.click(function() { alert(idx); });
    table.append(row);
  })(idx);
}

现在,给你是停止做这样的事件绑定,并开始使用jQuery活或委托API。这样,您可以为表中的所有行设置单个处理程序。给每行idx值作为一个id或一个类元素或某事,使你可以在处理程序中拉出来。 (或者我想你可以把它存储在数据expando。)

Now, the real advice I'd like to give you is to stop doing your event binding like that and to start using the jQuery "live" or "delegate" APIs. That way you can set up a single handler for all the rows in the table. Give each row the "idx" value as an "id" or a "class" element or something so that you can pull it out in the handler. (Or I guess you could stash it in the "data" expando.)

这篇关于如何在JavaScript中复制变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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