开发者

JQuery Dialog : How to find clicked button inside the button clicked event

Im currently defining a variable no. of buttons for a jquery dialog like this

    var buttonNames = buttonNamesString.split("|");
    var buttonsOpts = {};
    for (i = 0; i < buttonNames.length; i++) {
       buttonsOpts[buttonNames[i]] = function() { $(this).dialog("close");__doPostBack(postbackControlID, buttonNames[i]);}
    }

And initializing the dialog like this. (Notice the line buttons: buttonsOpts. Thats how I pass the variable no. of buttons)

开发者_如何学JAVAvar parentElement = popupControl.parent();            
            popupControl.dialog({ 
                                autoOpen: false, 
                                modal: true,
                                buttons: buttonsOpts,                                
                                hide: "explode",
                                open:function(type, data){
                                    $(this).parent().appendTo(parentElement);  
                                    popupControl.css({visibility: "visible"});                                          
                                }  
                                });

The problem is when a button in the dialog is clicked buttonNames[i] returns nothing in the line since i has been incremented to its maximum value.

function() { $(this).dialog("close");__doPostBack(postbackControlID, buttonNames[i]);}

Can we access the object which fires an event from inside the event code in Javascript like we do using the sender object in .Net events. That would solve the poblem.

How can I overcome this? Thanks in advance.


The problem is that you're using a closure on a loop iterated variable. This should solve it by changing the scope of the index.

for (i = 0; i < buttonNames.length; i++) {
       var index = i;
       buttonsOpts[buttonNames[index]] = function() { $(this).dialog("close");__doPostBack(postbackControlID, buttonNames[index]);}
    }

The longer answer to your question is that you're generating functions that all reference the same number variable, i. Therefor, in the end of your loop, all of your functions are set to buttonNames.length. Since you have no button in the array defined at buttonNames[buttonNames.length], you get undefined.

note: the temp variable at buttonOpts[buttonNames[index]] isn't required, it's just there for consistency

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜