Div Create dynamic and click
-
Legend create dynamic , I used jquery for create Legend GUI with click callback. each div have ID. expectation is while clicks div, the corresponding ID want to show. But here its showing only at last created div id only
for (var i = 0; i < 3; i++) {
var id = "test" + i;
$("", {
"id": id,
"style": "width:30px; height:30px cursor:pointer; border:1px solid Green ;padding:1px; background-color:Green",
click: function() {
alert("ID = "+ id);
}
}).appendTo("#legend"); -
Legend create dynamic , I used jquery for create Legend GUI with click callback. each div have ID. expectation is while clicks div, the corresponding ID want to show. But here its showing only at last created div id only
for (var i = 0; i < 3; i++) {
var id = "test" + i;
$("", {
"id": id,
"style": "width:30px; height:30px cursor:pointer; border:1px solid Green ;padding:1px; background-color:Green",
click: function() {
alert("ID = "+ id);
}
}).appendTo("#legend");The problem is the function you created doesn't capture the value of the variable id, but the reference to that variable via a closure. To get a function that captures the current value of id create a function called createFunc(id) like this:
function createFunc(id)
{
var tmp = id;
return function() { alert("ID = " + tmp); };
}then use it in your code like this:
... click: createFunc(id); ...
Cheers!
—MRB
modified on Wednesday, July 6, 2011 12:15 PM