写轮播图点击下方圆点banBtnLi[i],切换到第i个图片
banBtnLi是按钮集合,假设banBtnLi.length是4
banImhLi是装图片的li,自然banImgLi.length也是4
点击banBtnLi[i]先清空所有banBtnLi和banImgLi 的class,再给相应的banBtnLi和banImgLi加上class
因为在function中获取不到外层for中的i值,所以要定义一个banBtnLi的属性banBtnLi.index,把i的值赋给它,
在onmouseover方法中this就是指banBtnLi[i],用this.index就可以获取到外层i的值
方法如下
for(var i=0;i<banBtnLi.length;i++){
banBtnLi[i].index = i;
banBtnLi[i].onmouseover = function () {
for (var j=0;j<banImgLi.length;j++) {
banImgLi[j].className = "";
banBtnLi[j].className = "";
}
banImgLi[this.index].className = "banner-present";
banBtnLi[this.index].className = "banner-btn-present";
}
};
这里给出各个变量的输出值,更容易理解每个变量应该等以几
for(var i=0;i<banBtnLi.length;i++){
banBtnLi[i].index = i;
banBtnLi[i].onmouseover = function () {
for (var j=0;j<banImgLi.length;j++) {
banImgLi[j].className = "";
banBtnLi[j].className = "";
} console.log(banBtnLi[i]);//undefined
// console.log(banBtnLi[i].index);//报错
console.log(i);//
console.log(j);//
console.log(this.index);//指几是几:0或1或2 banImgLi[this.index].className = "banner-present";
banBtnLi[this.index].className = "banner-btn-present";
}
};