如何在Javscript中正确迭代对象的子对象

时间:2019-01-23 22:32:28

标签: javascript

对象清单具有3个子对象foo,bar,air。我想为每个子对象创建一个按钮,该按钮将触发特定于该子对象的东西。

//Inventory of Items
var inventory = {
    foo:    {title: 'data foo'},
    bar:    {title: 'data bar'},
    air:    {title: 'data air'},
};

//Create button for each item in the inventory and set the button's action to return the item title.
function loop_inventory(){
    for (item_name in inventory){
        var item = inventory[item_name];
        var button = document.createElement('button');
        button.innerHTML = item_name;
        button.onclick = function(){alert(item.title);};
        holder.appendChild(button);
    }
}
loop_inventory();

我希望每个名为“ foo”,“ bar”和“ air”的按钮提醒其相应数据。最终发生的事情是,它们每个都警告“数据广播”。我还尝试为每个子对象赋予唯一的函数属性,然后将其设置为按钮的onclick,但这也不起作用。

我确定我正在做一些非常愚蠢的和非JavaScript的操作,例如某个地方,但是我无法弄清楚。

0 个答案:

没有答案