Javascript - passing by value in a loop
I have the following code inside a class:
this.buttons = {
cancelButton:{buttonId: "cancelButton", buttonText:"Cancel", buttonClick: function(){alert('Cancel');}},
confirmButton:{buttonId: "confirmButton", buttonText:"Ok", buttonClick: function(){alert('Ok');}}};
}
for(var button in buttons){
var buttonId = buttons[button].buttonId;
var buttonClick = buttons[button].buttonClick;
var buttonText = buttons[button].buttonText;
$("#confirmDialogWrapper #buttons").append('<button type="button" id="'+buttonId+'" class="button_neutral"><div class="btn_black"><div class="btn_开发者_JS百科black_inner">'+buttonText+'</div></div></button>');
$("#confirmDialogWrapper #"+buttonId).click(function(){
buttonClick();
$("#popup_background").fadeOut(200);
$("#confirmDialogWrapper").remove();
delete this;
});
My problem is that each button gets the "buttonClick function" of the final iteration element. In the above example each button will alert "Ok" - which is not ok :) However the buttonText value is correct.
Any help would be appreciated.
Use another function to create a new scope:
for(var button in buttons){
(function(button)
{
var buttonId = buttons[button].buttonId;
var buttonClick = buttons[button].buttonClick;
var buttonText = buttons[button].buttonText;
$("#confirmDialogWrapper #buttons").append('<button type="button" id="'+buttonId+'" class="button_neutral"><div class="btn_black"><div class="btn_black_inner">'+buttonText+'</div></div></button>');
$("#confirmDialogWrapper #"+buttonId).click(function(){
buttonClick();
$("#popup_background").fadeOut(200);
$("#confirmDialogWrapper").remove();
delete this;
});
})(button);
}
精彩评论