【问题标题】:display list with the JS DOM使用 JS DOM 显示列表
【发布时间】:2021-05-29 02:07:36
【问题描述】:

我有一个包含 8 个对象的数组。我正在使用循环来获取每个项目的值。我想在我的 html 文件中的 div 中显示它们。我只想显示其中的 4 个(暂时!但在我想在删除它们时自动替换这些图像之后)。

我知道我可以使用 splice() 方法或 slice() 方法。但我想知道是否可以在不创建新数组的情况下做到这一点?因为我希望我的 for 循环一次将所有对象转换为图像。

const data = [
   {
   image_name: "Image1",
   image_id: "0",
   source: "images/img1.png",},
  {
   image_name: "Image2",
   image_id: "1",
   source: "images/img2.png",
  },
  {
    image_name: "Image3",
    image_id: "2",
    source: "images/img3.png",
  },
  {
    image_name: "Image4",
    image_id: "3",
    source: "images/img4.png",
  },
  {
    image_name: "Image5",
    image_id: "4",
    source: "images/img5.png",
  },
  {
    image_name: "Image6",
    image_id: "5",
    source: "images/img6.png",
  },
  {
    image_name: "Image7",
    image_id: "6",
    source: "images/img7.png",
  },
  {
    image_name: "Image8",
    image_id: "7",
    source: "images/img8.png",
  }
]
      
for (let i = 0; i < data.length; i++) { // data.length returns 8
  // creation of the images
  let images = document.createElement('img')
  images.setAttribute('class', 'image')
  document.querySelector('.container-image-to-place').append(images)// It displays automatically the 8 images
}

images = document.querySelectorAll('.image')
// assign each values to the good image
data.forEach(({source, image_name, image_id}, i) => {
  images[i].src = source
  images[i].alt = image_name
  images[i].id = image_id
})
<body>
<div class="container-image-to-place">
<!-- the images are displayed here -->
</div>
</body>

【问题讨论】:

  • 我不太明白你想要做什么。为什么你只想循环 4 个项目?这是基于什么标准?无论哪种方式,一种解决方案是在您的 data.forEach 中设置一个条件
  • 你的问题到底是什么?
  • splice 不会产生新的数组...当然,只要做到if (i &lt; 4) images.classList.add('show'); 并添加像.image { display: none; } .image.show {display: inline;} 这样的CSS 就足够简单了
  • @ElRonnoco。我想将我的所有对象更改为 (以 html 方式),然后显示前 4 个,但如果我删除这 4 个中的一个,我希望下一个 自动取代它。我想要像一行图像这样的东西,当我将一个图像拖放到另一个 div 中时(我从数据数组中删除了这个 img/obj。我知道如何通过拖放事件来做到这一点!)另一个图像左边 3 出现在屏幕上。在我的代码中,如果我放了 i

标签: javascript html arrays dom


【解决方案1】:

我不太明白您要达到的目标。但是如果你想在不修改数组的情况下处理前 4 个项目,你可以这样做......

  data.forEach(({source, image_name, image_id}, i) => {
    if (i < 4) {
        images[i].src = source
        images[i].alt = image_name
        images[i].id = image_id
    }
  });

然而,这并不是特别优雅,就像您有一个包含 1000 个对象的数组一样,它需要为每个对象执行条件。正如您所建议的,最好使用.slice...

  // untested!
  data.slice(0, 4).forEach(({source, image_name, image_id}, i) => {
    images[i].src = source
    images[i].alt = image_name
    images[i].id = image_id
  });

这不会改变您的 data 数组,但会创建前 4 个项目的新副本。

【讨论】:

    【解决方案2】:

    如果您想遍历所有图像,使用 for 循环很有用,但是如果您只想遍历其中 4 个,为什么不使用这样的 while 循环:

    while (i < 4) {
      // code block to be executed
      i++;
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 1970-01-01
      • 2023-04-02
      • 2019-05-02
      • 1970-01-01
      • 2013-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多