JQuery 对话框:如何在按钮单击事件中查找单击的按钮
我目前正在定义一个变量号。像这样的 jquery 对话框的按钮
var buttonNames = buttonNamesString.split("|");
var buttonsOpts = {};
for (i = 0; i < buttonNames.length; i++) {
buttonsOpts[buttonNames[i]] = function() { $(this).dialog("close");__doPostBack(postbackControlID, buttonNames[i]);}
}
并像这样初始化对话框。 (注意行按钮:buttonsOpts。这就是我传递按钮变量数量的方式)
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"});
}
});
问题是,当单击对话框中的按钮时,buttonNames[i] 在行中不返回任何内容,因为 i 已增加到其最大值。
function() { $(this).dialog("close");__doPostBack(postbackControlID, buttonNames[i]);}
我们可以像使用发送者对象一样从 Javascript 中的事件代码内部访问触发事件的对象吗在 .Net 事件中。这样问题就解决了。
我怎样才能克服这个问题?提前致谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是您在循环迭代变量上使用闭包。这应该通过改变索引的范围来解决。
您的问题的较长答案是您正在生成全部引用相同数字变量
i
的函数。因此,在循环结束时,所有函数都设置为buttonNames.length。由于在buttonNames[buttonNames.length]处定义的数组中没有按钮,所以你会得到undefined
。注意:
buttonOpts[buttonNames[index]]
中的临时变量不是必需的,它只是为了保持一致性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.
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 getundefined
.note: the temp variable at
buttonOpts[buttonNames[index]]
isn't required, it's just there for consistency