I have a situation whereby, i need to create buttons dynamically and i need to attached an onclick event to each of them. All of the above is done fine. However, when one o
Try to use self-invocation
(function (x, poly, map) {
document.getElementById(x).onclick=function test(){
animate(poly,map);
}
})(x, poly, map);
You are declaring the map
variable without the var
keyword so it's being created in the global scope, so there is only one map
variable that gets it's value over-written each loop.
for(var k=0;k<arr_altern.length;k++){
(function (k) {
my_div=create_div_interchange(arr[i],1,78,visited_bus,interchange_arr,arr_altern[k],null, my_interchange_array);
$('#results').append(my_div);
var x = 'animate' + div_id,
v = '#animater' + div_id,
map = create_map(div_id),
poly = retrieve_results_edges(bus_stops_visited, map),
strVar = '<span class="animate"><input type="button" id="' + x + '" name="animate" value="Animate" /><\/span>';
$(v).append(strVar);
document.getElementById(x).onclick=function test(){
animate(poly,map);
}
set_map(map);
set_polyline_color(my_traversed_edge,map);
})(k);
}
Running your code inside of an IIFE (Immediately-Invoked Function Expression) will create a new scope for the code within it. This allows you to declare variables at the time of running and they will hold their value into the future (for instance they will be available to event handlers that fire in the future). Notice I used the var
keyword when declaring all the variables so they are created in the current scope.
You could also use $.each()
to scope your code:
$.each(arr_altern, function (k, val) {
my_div=create_div_interchange(arr[i],1,78,visited_bus,interchange_arr,arr_altern[k],null, my_interchange_array);
$('#results').append(my_div);
var x = 'animate' + div_id,
v = '#animater' + div_id,
map = create_map(div_id),
poly = retrieve_results_edges(bus_stops_visited, map),
strVar = '<span class="animate"><input type="button" id="' + x + '" name="animate" value="Animate" /><\/span>';
$(v).append(strVar);
document.getElementById(x).onclick=function test(){
animate(poly,map);
}
set_map(map);
set_polyline_color(my_traversed_edge,map);
});
You can use jQuery proxy
var buttons = $("a");
for (var i = 0; i < buttons.length; i++){
$(buttons[i]).unbind("click").click(
$.proxy(
function(){
alert(this);
return false;
},
i
)
);
}
or capture your arguments by creating new function
var buttons = $("a");
for (var i = 0; i < buttons.length; i++){
$(buttons[i]).unbind("click").click(
function(arg){
return function(){
alert(arg);
return false;
};
}(i)
);
}
Just run one of this examples in firebug console to see the effect.