首页 > 解决方案 > 如何循环遍历 HTML 元素

问题描述

此代码使得当用户单击其中一种颜色(color1-4)时,它会设置display所有鞋子的 CSS 属性,none但单击的颜色除外,其display设置为block. 代码看起来很脏,雇主不会批准。

我将如何制作一个 for 循环,或者以其他方式使代码更清晰?

color2.addEventListener('click', () => {
    shoe.style.display = "none";
    shoe3.style.display = "none";
    shoe5.style.display = "none";
    shoe2.style.display = "block";
    console.log('u removed it and added another');
});

color3.addEventListener('click', () => {
    shoe.style.display = "none";
    shoe3.style.display = "none";
    shoe5.style.display = "none";
    shoe2.style.display = "none";
    shoe3.style.display = "block";
    console.log('u removed it and added another');
});

color4.addEventListener('click', () => {
    shoe.style.display = "none";
    shoe3.style.display = "none";
    shoe5.style.display = "none";
    shoe3.style.display = "none";
    shoe5.style.display = "block";
    console.log('u removed it and added another');
});

color1.addEventListener('click', () => {
    shoe.style.display = "block";
    shoe2.style.display = "none";
    shoe3.style.display = "none";
    shoe4.style.display = "none";
    shoe5.style.display = "none";
    console.log('u removed it and added another');
});

color2.addEventListener('click', () => {
    shoe.style.display = "none";
    shoe3.style.display = "none";
    shoe5.style.display = "none";
    shoe2.style.display = "block";
    console.log('u removed it and added another');
});

标签: javascriptfor-loopdom

解决方案


请检查这个,看看你是否可以修改你的代码,如下所示:

const colorList = [color1, color2, color3]; // you can add more
const shoeList = [shoe1, shoe2, shoe3]; // you can add more
[color1, color2, color3].forEach((color, colorIndex) => {
  color.addEventListener('click', () => {
    shoeList.forEach((shoe, shoeIndex) => {
      if (colorIndex === shoeIndex) {
        shoe.style.display = "block";
      } else {
        shoe.style.display = "none";
      }
    });
  });
});

推荐阅读