开发者

How to copy a variable in JavaScript?

开发者 https://www.devze.com 2022-12-22 03:01 出处:网络
I have this JavaScript code: for (var idx in data) { var row = $(\"<开发者_运维技巧;tr></tr>\");

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.


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


Check out jquery's data() method:

http://api.jquery.com/jQuery.data/

Description: Store arbitrary data associated with the specified element.

0

精彩评论

暂无评论...
验证码 换一张
取 消