Javascript 单击后更改跨度的颜色

Javascript 单击后更改跨度的颜色,javascript,Javascript,功能测试(){ var span=document.querySelectorAll('span'); 对于(var i=0;i 您正在将事件设置为整个跨度集合。您应该设置为单个元素 span[i].addEventListener('click', function(){ 除了上面的答案,我还建议在DocumentReady上运行测试 $( document ).ready(test); 更新了带有修复程序的代码笔: 功能测试(){ var span=document.querySelec

功能测试(){
var span=document.querySelectorAll('span');
对于(var i=0;i
您正在将事件设置为整个跨度集合。您应该设置为单个元素

span[i].addEventListener('click', function(){

除了上面的答案,我还建议在DocumentReady上运行测试

$( document ).ready(test);
更新了带有修复程序的代码笔:

功能测试(){
var span=document.querySelectorAll('span');
span.forEach((项目)=>{
item.addEventListener('单击',()=>{
让样式=getComputedStyle(项目);
styles.backgroundColor='rgb(255,255,255)'?item.style.backgroundColor='yellow':item.style.backgroundColor='black';
});
});
}
test();
.def.def2{
背景颜色:橙色
}
分区#ya{
背景颜色:紫色
}
跨度{
背景色:#ffffff
}

悲哀的
第一组
第二组
第二组
悲哀的

测试测试
1-JavaScript总是将HTML中的白色背景装饰为null 用于印刷目的

因此,如果您试图匹配的背景是白色的
然后更换

this.style.backgroundColor=='#ffffff'?..…等;

为此:

this.style.backgroundColor === "" ? this.style.backgroundColor = 'yellow'
     : this.style.backgroundColor="#000000";
其他方式,如果您尝试匹配的背景为而非白色
然后您可以使用条件normal
element==“color code here”

2-最后,正如其他人提到的,在span回调函数前面添加循环,如下所示:


您好,非常感谢,但我很困惑。既然我设置了“整个系列”,那么逻辑上所有跨度都应该设置为黑色吗?
$( document ).ready(test);
this.style.backgroundColor === "" ? this.style.backgroundColor = 'yellow'
     : this.style.backgroundColor="#000000";
span[i].addEventListener('click', function(){ ... etc