javascript - 如何循环遍历 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');
});
解决方案
请检查这个,看看你是否可以修改你的代码,如下所示:
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";
}
});
});
});
推荐阅读
- react-native - 使用 OpenStreetMap 反应原生离线地图
- node.js - Node、Express - 索引文件未正确调用文件
- php - Google Analytics V4 Hello Analytics + 在运行 BatchGet() 之前检查请求权限状态
- sql-server - 二父表一子表关系
- svelte - 如何绑定苗条的动态组件值
- ios - 使用 AudioConverter 将 PCM 转换为 AAC 并使用 AVAssetWriter 写入 .mp4 文件时音频失真
- copy-paste - tmux 中的鼠标选择将所有选择的内容连接到剪贴板
- if-statement - 根据值设置的百分比计算成功率
- java - 在某些情况发生后停止线程 ScheduledThreadPoolExecutor
- prolog - 为什么它说我的谓词 block/3 没有被调用?