【问题标题】:If div children don't have same text content then do action如果 div 子项没有相同的文本内容,则执行操作
【发布时间】:2021-03-24 08:56:55
【问题描述】:

我正在尝试基于 JSON 文件对象为成分过滤栏创建 DOM 元素。

问题是相同的成分可以出现在多个对象中,在这种情况下,它应该只创建一次 dom 元素,而不是每次出现成分。

我已尝试使用 childNodevalueinnerHTML !===,但无法找到解决方案。它要么根本不创建任何元素,要么所有元素都有重复项。

有什么想法吗?

这里有一个 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.....

实际结果是:

预期结果是:

【问题讨论】:

  • 请点击编辑,[&lt;&gt;]sn-p编辑器并创建minimal reproducible example
  • 提示:使用数组、集合或对象来跟踪您已经看到的值
  • 这个问题本身就缺乏很多理解成分……
  • 我刚刚添加了一个极简的CodePen
  • @charlietfl 我试过了 (codepen.io/enukeron/pen/ExgZoLa) 但似乎也没有用

标签: javascript json for-loop if-statement dom


【解决方案1】:

您可以创建如下函数:

function filterIngredients(recipes){
  let return_arr = [];
  recipes.forEach((recipe, index, array)=>{
    let ingredients = recipe["ingredients"];
    ingredients.forEach((ingredient, index, inner_array)=>{
      if(!return_arr.includes(ingredient["ingredient"])){
        return_arr.push(ingredient["ingredient"]);
      }
    });
  });
  return return_arr;
}

然后调用函数如下:

var ingredients = filterIngredients(recipes);

然后您可以遍历ingredients 并根据需要在 div 中显示它们(希望这是您首先想要的)。 这是我实现它的笔的链接: https://codepen.io/AnirudhMS/pen/MWjJQgg?editors=1010

【讨论】:

  • 这就是我最终在@charlietfl 的建议下所做的,非常感谢:)
猜你喜欢
  • 1970-01-01
  • 2016-08-20
  • 2018-09-19
  • 1970-01-01
  • 2015-11-18
  • 2011-12-29
  • 1970-01-01
  • 2015-07-02
  • 1970-01-01
相关资源
最近更新 更多