61,112
社区成员
发帖
与我相关
我的任务
分享
<span>a</span><span>b</span><span>c</span>
var div = document.getElementById('div');
var span = div.getElementsByTagName('span');
for(var i = 0; i < span.length; i++){
span[i].onclick = function(){
if(this.className.length){
this.className = '';
} else {
this.className = 'red';
}
}
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
<style type="text/css">
#div{ width:320px;margin: 30px auto;}
#div span{ display:inline-block; width:100px; height:30px; line-height:30px; text-align:center; border:1px solid #ccc;cursor: pointer;}
#div span:hover{background: #f1f1f1;}
#div span.red{background: #e00;color: #fff; font-weight:bold;}
</style>
</head>
<body>
<div id="div">
<span>a</span><span>b</span><span>c</span>
</div>
<script>
(function(){
var div = document.getElementById('div');
var span = div.getElementsByTagName('span');
for(var i = 0; i < span.length; i++){
span[i].onclick = function(){
if(this.className.length){
this.className = '';
} else {
this.className = 'red';
}
}
}
}());
</script>
</body>
</html>