开发者

Javascript - passing by value in a loop

开发者 https://www.devze.com 2023-01-06 10:00 出处:网络
I have the following code inside a class: this.buttons = { cancelButton:{buttonId: \"cancelButton\", buttonText:\"Cancel\", buttonClick: function(){alert(\'Cancel\');}},

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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消