gpt4 book ai didi

javascript - 如何获取另一个对象内的对象的名称?

转载 作者:行者123 更新时间:2023-11-30 07:00:24 25 4
gpt4 key购买 nike

我正在开发一个打开自定义对话框的项目。我试图在 settings 对象中做到这一点,您可以将自定义按钮的名称指定为对象的名称,其中包含按钮的信息。我想知道,如何获取按钮名称的名称?

我目前的代码是这样的:

function resetTools() {
Dialogue.open({
message: "Are you sure you want to reset all chat rooms?",
buttons: {
yes: {
styleSheetClass: "dangerbtn",
onclick: function() {
// Do stuff here
}
},
no: {
onclick: function() {
// Do other stuff here
}
}
}
})
}

var Dialogue = {
open: function(settings) {
var message = settings.message;
var buttons = message.buttons;
for (var i = 0; i < buttons.length; i++) {
var cls = buttons[i].styleSheetClass.length ? buttons[i].styleSheetClass + " dialogueButton" : "dialogueButton";
$(".dialogue .buttons").append('<div class="' + cls + '">' + +'</div>');
}
}
}

感谢您的帮助。

最佳答案

您可以使用 for...in 循环来获取对象的键,并记住使用 hasOwnProperty 来测试属性是否存在

for (var key in buttons) {
if (buttons.hasOwnProperty(key)) {
// key could be 'yes' or 'no'
// access the value using buttons[key]
}
}

或者你可以使用es5.1中引入的Object.keys

Object.keys(buttons).forEach(function(key) {
// do something with buttons[key]
})

关于javascript - 如何获取另一个对象内的对象的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33752496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com