"); row.click(function() { a...">

How to copy a variable in JavaScript?

I have this JavaScript code:

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

So, I look through the array, dynamically creating the rows (the part where I create the cells is omitted, since this is not important). The important thing is that I create a new function that includes the idx variable.

However, idx is just a link, so at the end of the loop, all lines have the same function, and all notify the same value.

One way to solve this problem at the moment:

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

and in the calling code I call

row.click(GetRowClickFunction(idx));

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

While the problem itself is not specific to jQuery (it is related to the closure / scope of JavaScript), I am using jQuery, and therefore the jQuery solution is ok if it works.

+3
2

:

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

, , - API- jQuery "live" "delegate". , . "idx" "id" "class" - , . (, , "data" expando.)

+9
+2

Source: https://habr.com/ru/post/1735482/


All Articles