【发布时间】:2021-03-24 08:56:55
【问题描述】:
我正在尝试基于 JSON 文件对象为成分过滤栏创建 DOM 元素。
问题是相同的成分可以出现在多个对象中,在这种情况下,它应该只创建一次 dom 元素,而不是每次出现成分。
我已尝试使用 childNode、value、innerHTML 和 !===,但无法找到解决方案。它要么根本不创建任何元素,要么所有元素都有重复项。
有什么想法吗?
这里有一个 codePen 来帮忙:https://codepen.io/enukeron/pen/eYdgyzx
我还尝试使用一个数组来跟踪此 codepen 中看到的值: https://codepen.io/enukeron/pen/ExgZoLa
JS:
const ingredientDropdown = document.getElementById('ingredientDropdown');
for(var j = 0; j < IngredientList.length; j++) {
if (ingredientDropdown.children.textContent !== IngredientList[j].ingredient) {
var ingredientSearchItems = document.createElement("p");
ingredientSearchItems.textContent = IngredientList[j].ingredient;
ingredientDropdown.appendChild(ingredientSearchItems);
}
}
JSON 文件格式如下:
{
"id": 49,
"name": "Tropical smoothie",
"servings": 4,
"ingredients": [
{
"ingredient": "Bananas",
"quantity": 2
},
{
"ingredient": "Kiwis",
"quantity": 3
},
{
"ingredient": "Mango",
"quantity": 1
},
{
"ingredient": "Pineapple",
"quantity": 4,
"unit":"slices"
},
{
"ingredient": "Honey",
"quantity": 2,
"unit": "tablespoons"
}
],
"time": 0,
"description":"Chop the fruit. Liquefy in the blender. Chill. Serve",
"appliance": "Blender",
"ustensils":["couteau", "verres"]
}, etc.....
【问题讨论】:
-
请点击编辑,
[<>]sn-p编辑器并创建minimal reproducible example -
提示:使用数组、集合或对象来跟踪您已经看到的值
-
这个问题本身就缺乏很多理解成分……
-
我刚刚添加了一个极简的CodePen
-
@charlietfl 我试过了 (codepen.io/enukeron/pen/ExgZoLa) 但似乎也没有用
标签: javascript json for-loop if-statement dom