87,963
社区成员
发帖
与我相关
我的任务
分享
var spans=document.querySelectorAll('span');
for(var i=0;i<spans.length;i++){
spans[i].onclick=function(){
this.classList.toggle('change');
}
}
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<style>
.change{
color: red;
}
</style>
</head>
<body>
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<script>
[].slice.call(document.querySelectorAll('span')).forEach(function(item,index){
item.onclick=function(){
item.innerHTML=index;
item.classList.toggle('change');
}
})
</script>
</body>
</html>
可以用foreach 也可以dom[i]改成this