如何在JavaScript中复制变量?(How to copy a variable in JavaScript?)

编程入门 行业动态 更新时间:2024-10-26 09:30:40
如何在JavaScript中复制变量?(How to copy a variable in JavaScript?)

我有这个JavaScript代码:

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

所以我正在查看一个数组,动态创建行(我创建单元的部分被忽略,因为它不重要)。 重要的是我创建了一个包含idx变量的新函数。

但是,idx只是一个引用,所以在循环结束时,所有行都具有相同的功能,并且所有行都提醒相同的值。

我现在解决这个问题的一个方法就是这样做:

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

并在我打电话的调用代码中

row.click(GetRowClickFunction(idx));

这工作,但有点难看。 我想知道是否有更好的方法来复制循环内的idx的当前值?

虽然问题本身并不是jQuery特有的(它与JavaScript闭包/作用域有关),但我使用jQuery,因此只有jQuery解决方案才行。

I have this JavaScript code:

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

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.

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); } }

and in the calling code I call

row.click(GetRowClickFunction(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?

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”或“class”元素或其他内容,以便您可以在处理程序中将其拉出。 (或者我想你可以把它存储在“数据”expando中。)

You could put the function in your loop:

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

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.)

更多推荐

本文发布于:2023-07-31 19:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1347294.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   如何在   variable   JavaScript   copy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!