用户单击时如何从 jquery ui 对话框中获取按钮 ID 的值?

How can I get value of the button id from jquery ui dialog when user click?

我想动态创建一个 jQuery UI 对话框。对话框中的按钮数量取决于我的 JSON 数据。当用户点击它时,我需要按钮 ID。

var deviceInfo = {
    "devices": [{ "deviceID": "11", "devicename": "test12" },
                { "deviceID": "12", "devicename": "test12" }]
};

for (var x in deviceInfo["devices"]) {
    arrButtons.push({
        text: "DeviceID:" + deviceInfo["devices"][x]["deviceID"], 
              id: deviceInfo["devices"][x]["deviceID"], click: function () {
            currentDeviceID = deviceInfo["devices"][x]["deviceID"];
            console.log("selected id:", currentDeviceID);
            $(this).dialog("close");
        }
    });
}

showDeviceID = function (dID) {
    console.log("deviceID", dID);
}

$("#dialog").dialog({
    modal: true,
    dialogClass: 'no-close',
    show: {
        effect: "blind",
        duration: 1000
    },
    hide: {
        effect: "explode",
        duration: 1000
    },
    buttons: arrButtons
});

每次我得到最后一个ID。你能帮帮我吗?

变化:

for (var x in deviceInfo["devices"]) {

    arrButtons.push({
        text: "DeviceID:" + deviceInfo["devices"][x]["deviceID"], id: deviceInfo["devices"][x]["deviceID"], click: function () {
            currentDeviceID = deviceInfo["devices"][x]["deviceID"];

            console.log("selected id:", currentDeviceID);

            $(this).dialog("close");
        }
    });

}

对于:

for (var x in deviceInfo["devices"]) {
    var device = deviceInfo["devices"][x]["deviceID"];

    arrButtons.push({
        device: {
            click: function () {
                console.log("selected id:", device);
            }
        }
    });

}

只需使用 click 处理程序的 event 属性。

$('button').click(function(e)
{
   e.target.id; // gives you the id of the button clicked.
}