点击p标签切换颜色
设置2n+1为红色,2n+2为蓝色
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p >1</p>
<p >2</p>
<p >3</p>
<p >4</p>
<p >5</p>
<p >6</p>
<p >7</p>
<p >8</p>
<p >9</p>
<p >10</p>
<p >11</p>
<p >12</p>
<p >13</p>
<script type="text/javascript" >
var ptag = document.querySelectorAll("p");
for(let i=0;i<ptag.length;i++) {
//数值越界,2*i+3>ptag.length 所以报错 所以
if(2*i+1>=ptag.length-1) {
break;
}
ptag[2*i+1].style.color = "blue";
ptag[2*i+2].style.color = "red";
}
ptag.forEach((el)=>{//遍历元素,传参el进去,el代表p标签
el.onclick=function() {//添加点击事件
//console.log(this)//this表示被点击的事件
if(this.style.color == "blue") {
this.style.color = "red";
}else{
this.style.color = "blue"
}
}
})
</script>
</html>