我有一个 Javascript 对象数组。在不使用任何 HTML 的情况下,我需要为数组中的每个对象添加按钮。我知道如何在 Javascript 中制作按钮,如下所示:
//Create the button
var button = document.createElement("button");
但我不确定如何为数组中的每个对象添加一个。这是我的数组的数组代码:
var items = [
{
name: "cake",
price:"7.00",
quantity:4
},
{
name:"fries",
price:"8.00",
quantity:3
},
{
name:"brownie",
price:"5.00",
quantity:2
},
{
name:"candy",
price:"9.00",
quantity: 12
},
]
我的数组中有更多对象,但我只添加了一些对象以最大程度地减少问题,并且我希望将“名称”用作按钮的标签。我知道我需要使用 for 循环,但我不知道在循环中写什么。我尝试在 Google 上搜索这个问题,但我找不到任何显示如何在 Javascript 中执行此操作的内容,我只找到了我尚未学习的其他语言。我也已经有了这个链接:https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
我想将该按钮用作“点赞”按钮。每个项目都有一个按钮,当单击该按钮时,该项目将显示在列表中。例如:用户喜欢蛋糕和薯条,所以我的“列表”会说蛋糕和薯条。每个按钮只能单击一次。这类似于将商品添加到购物护理中的概念,但我将其用于喜欢的商品。
最佳答案
您可以使用 forEach() 数组方法创建一个循环,例如:
const parentElement = document.querySelector('body'); // DOM location when buttons will be added
items.forEach(function(item) {
const button = document.createElement("button");
button.innerText = item.name;
parentElement.appendChild(button); // to add new element to DOM
})
关于javascript - 创建多个按钮 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60471047/