如何调用回调中定义的数组?

问题描述 投票:0回答:1

我需要弄清楚如何调用回调函数中定义的对象数组。我正在尝试使用 forEach 循环的对象数组来显示每个对象并将其添加到 HTML 中所需的 div,因为它循环通过。

这是我在定义 const fetchProducts 后尝试的方法。在 HTML 文件中,有一个类为“fetch-products”的按钮和一个类为“product-container”的 div。

document.querySelector('button.fetch-products').addEventListener("click", function() {
  
  fetchProducts.foreach(function(item){
    document.querySelector('div.product-container').innerHTML = item;
  });
});

我收到一条错误消息 Uncaught TypeError: fetchProducts.foreach is not a function。

这里是调用对象数组的地方

const fetchProducts = (callback) => {
  setTimeout(() => {
    callback([
      {
        brand: "Converse",
        productName: "Chuck Taylor All Star Hi Top Sneaker",
        image:
          "https://www.famousfootwear.com/blob/product-images/20000/69/92/4/69924_right_medium.jpg",
        price: 59.99,
        badge: "NEW"
      },
      {
        brand: "Nike",
        productName: "Lebron Witness V Basketball Shoe",
        image:
          "https://www.famousfootwear.com/blob/product-images/20000/50/18/9/50189_right_medium.jpg",
        price: 99.99
      },
      {
        brand: "Crocs",
        productName: "Women's Classic Clog",
        image:
          "https://www.famousfootwear.com/blob/product-images/20000/99/02/0/99020_right_medium.jpg",
        price: 49.99,
        badge: "NEW"
      },
      {
        brand: "Vans",
        productName: "Women's Asher Slip On Sneaker",
        image:
          "https://www.famousfootwear.com/blob/product-images/20000/51/17/3/51173_right_medium.jpg",
        price: 54.99,
        badge: "ONLINE ONLY"
      }
    ]);
  }, 200);
};
javascript callback addeventlistener foreach-object
1个回答
0
投票

要使用您显示的代码,您需要调用

fetchProducts
,并将其传递到回调函数中。 forEach 将进入该回调内部(并且它需要“E”的正确大写)。例如:

fetchProducts(products => {
  products.forEach(item => {
    document.querySelector('div.product-container').innerHTML = item;
  });
})
© www.soinside.com 2019 - 2024. All rights reserved.