如何在循环中将 n 个按钮分配给 jQuery 对话框

How do you assign n buttons to jQuery dialog in a loop?

本文关键字:分配 按钮 jQuery 对话框 循环      更新时间:2023-09-26

下面的代码做了一些奇怪的事情。 每当您单击对话框中的按钮时,您都会看到"test5"作为警报文本,而不是"test0"、"test2"、...每个按钮分别使用"test4"。 关于在循环中分配函数的某些事情不起作用。

var arrbuttons = [];
for (var i=0; i<5; i++) {
    arrbuttons.push({click: function() { alert('test'+i);}, text:'test'+i});
}
jQuery("#requestdialog").dialog(
    {
        title: "test",
        height: 250,
        width: 500,
        modal: true,
        buttons: arrbuttons
    }
这一切都

与范围和闭包有关:

var arrbuttons = [];
for (var j=0; j<5; j++) {
    (function(i) {
        arrbuttons.push({click: function() { alert('test'+i);}, text:'test'+i});
    })(j);
}
jQuery("#requestdialog").dialog(
    {
        title: "test",
        height: 250,
        width: 500,
        modal: true,
        buttons: arrbuttons
    }