我在类中有以下代码:
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_black_inner">'+buttonText+'</div></div></button>');
$("#confirmDialogWrapper #"+buttonId).click(function(){
buttonClick();
$("#popup_background").fadeOut(200);
$("#confirmDialogWrapper").remove();
delete this;
});
我的问题是每个按钮都会获得最终迭代元素的“buttonClick函数”。在上面的例子中,每个按钮都会提示“Ok” - 这不是正常的:) 但是buttonText值是正确的。
任何帮助都将不胜感激。
答案 0 :(得分:1)
使用其他功能创建新范围:
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);
}