问题:想获取aList 的点击次数,用于判断%==0,隐藏下拉列表,aList 是一个数组,先要获取数组的下标用于定位,然后判断被点击的次数。
var aList = document.querySelectorAll('.nav-list h2');
//console.log(aList);
var aHide = document.querySelectorAll('.hide');
var aIcon = document.querySelectorAll('.nav-list i');
var lastIndex = 0;
for(var i=0;i < aList.length;i++){
aList[i].index = i;
aList[i].onclick = function(){
//click += 1;
//console.log(click);
//清除上一次样式
aHide[lastIndex].style.height = 0;
aList[lastIndex].className = '';
aIcon[lastIndex].className = '';
//设置当前样式
aHide[this.index].style.height = 'auto';
//aHide[this.index].style.transition = '1s';
aList[this.index].className = 'on';
aIcon[this.index].className = 'on';
lastIndex = this.index;
}
}
你可以在for 循环外加一个计数变量,用于记录每一个数据被点了几下。下面是伪代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p>点击1</p>
<p>点击2</p>
<p>点击3</p>
<button>p被点了几下</button>
</body>
</html>
<script>
var num = []
var p_click = document.getElementsByTagName("p")
var button_click = document.getElementsByTagName("button")
for(i =0 ; i<p_click.length; i++){
p_click[i].index = i
p_click[i].onclick=function(){
if(num[this.index]){
num[this.index]++
}else{
num[this.index] = 1
}
}
}
// 获取每一个 p对应的点击次数
button_click[0].onclick=function(){
console.log(num)
}
</script>