这里有3个
<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'; } }}
test <span>a</span><span>b</span><span>c</span><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>
看看这个是不是你要的结果:
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'; } }}
test <span>a</span><span>b</span><span>c</span><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>