数组循环实现彩虹文字练习 代码运行问题求助
数组循环彩虹文字练习问题排查
现有代码错误点
- 选择器方法使用错误:
document.querySelector()只会返回匹配到的第一个元素,你需要获取h1标签下所有span元素,应该使用document.querySelectorAll('h1 span') - 循环内赋值对象错误:
for...of遍历中,每一轮拿到的rainbow才是当前要操作的单个span元素,你直接给spans集合设置样式不会生效 - 颜色赋值逻辑缺失:你给颜色赋值为空字符串,且没有关联题目给定的
colors彩虹色数组,无法实现需求
可正常运行的实现代码
基础for循环写法(更直观匹配索引)
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']; const spans = document.querySelectorAll('h1 span'); for(let i = 0; i < spans.length; i++) { spans[i].style.color = colors[i]; }
for of写法
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']; const spans = document.querySelectorAll('h1 span'); let colorIndex = 0; for(let rainbow of spans) { rainbow.style.color = colors[colorIndex]; colorIndex++; }
内容的提问来源于stack exchange,提问作者Rasik07
相关产品推荐
相关产品推荐

