我正在尝试创建餐厅菜单的移动 View 。菜单本身存储在menu
中以以下形式保存数据的变量
let menu = [
[
'Food Section', //i.e Appetizers
['Entry', 'Food Description' , 'Price'],
['Entry', 'Food Description' , 'Price']
]
[
'Food Section', //i.e Soup
['Entry', 'Food Description' , 'Price'],
['Entry', 'Food Description' , 'Price']
],
etc...
我希望网站本身显示带有食物部分的按钮(“开胃菜”按钮、“汤”按钮),单击所述按钮后,相应的食物条目将下拉并变得可见。现在我正在尝试创建 buttons
和divs
每个button
下的适当条目。我通过循环 menu
来做到这一点然后循环遍历每个 menu
元素。这是我的代码:
js:
let menu = [
[
'Appetizers',
['Fried Calamari', "", '$11.95'],
['Mussels', "Marinara, fra diavolo or bianco", '$12.95'],
['Calamari & Mussels', "Fra diavolo or marinara", '$12.95'],
['Hot Antipasto', "Two baked clams, two stuffed shells, two stuffed mushrooms, two fried shrimp & scallops in a seafood sauce", '$14.95'],
],
[
'Soups',
['Chicken Noodle','','$4.95'],
['Minestrone','','$4.95'],
['Lentil','','$5.95'],
['Pasta Fagioli','','$5.95'],
['Cheese Tortellini','','$6.95'],
]
//create html elements by looping through menu variable
for(i = 0; i < menu.length; i++){
for(j = 0; j < menu[i].length; j++){
if(j == 0){
foodSectionText = menu[i][j];
let btn = document.createElement("BUTTON");
btn.innerHTML = foodSectionText;
document.body.appendChild(btn); }
else{
menuEntry = menu[i][j];
console.log(menuEntry);
for(i = 0; i < menuEntry.length; i++){
div = document.createElement("DIV");
div.innerHTML = menuEntry[i];
document.body.appendChild(div);
}
}
}
}
上面的代码将创建:
<button>Appetizers</button>
<div>Fried Calamari</div>
<div></div>
<div>$11.95</div>
但随后抛出 Uncaught TypeError: Cannot read property 'length' of undefined
引用for(j = 0; j < menu[i].length; j++)
。为什么第二项是['Mussels', "Marinara, fra diavolo or bianco", '$12.95']
(以及所有后续项目)未正确渲染?另外,如果您对如何清理此过程有任何建议,请随时分享,我觉得我将以一种糟糕的方式实现这一点......
最佳答案
在第三个 for 循环中,您重复使用相同的循环计数器 i
。尝试使用不同的变量名称(在我的示例中我使用k
)
for(let i = 0; i < menu.length; i++){
for(let j = 0; j < menu[i].length; j++){
if(j == 0){
foodSectionText = menu[i][j];
let btn = document.createElement("BUTTON");
btn.innerHTML = foodSectionText;
document.body.appendChild(btn); }
else{
menuEntry = menu[i][j];
console.log(menuEntry);
for(let k = 0; k < menuEntry.length; k++){
div = document.createElement("DIV");
div.innerHTML = menuEntry[k];
document.body.appendChild(div);
}
}
}
}
关于javascript - 从嵌套数组创建 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58739447/