当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - 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)

var 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

分享给朋友:
您可能感兴趣的文章:
随机阅读: