代码及注释:
// 实现选项卡功能
function init() {
// TODO 待补充代码
const tabs = document.querySelectorAll('.tabs div')
const contents = document.querySelectorAll('#content div') //获取元素集合
tabs.forEach((item, index, arr) => { //第一层循环
item.addEventListener('click', () => { //给每个tab元素添加一个点击事件
arr.forEach((item2, index2) => { //第二层循环
item2.className = '' //1.先删掉所有元素的'active'类名
contents[index2].classList.remove('active')
})
item.className = 'active' //2.再给点击到的元素添加'active'类名
contents[index].classList.add('active')
})
})
}
init();
考点:
1.动态tab的思想:
排他思想:先把所有元素的样式去除,然后给目标的元素添加样式
口诀:干掉所有人,复活自己
2.array.forEach()
array.forEach(callbackFn(currentValue, index, arr), thisValue)
箭头函数 forEach((element, index, array) => { /* … */ })
参数 | 描述 |
---|---|
callbackFn(currentValue, index, arr) | 必需。 数组中每个元素需要调用的函数。 |
thisValue | 可选。传递给函数的值一般用 "this" 值。 如果这个参数为空, "undefined" 会传递给 "this" 值 |
参数 | 描述 |
---|---|
currentValue | 必需。当前元素 |
index | 可选。当前元素的索引值。 |
arr | 可选。当前元素所属的数组对象。 |
不支持continue、break,没有返回值,不改变原数组(尽管在回调中会改变原数组)
tip:这道题目很坑,tab元素需要将.red、.green等颜色类名删掉才能通过