下表具有某些类型的类。我想通过单击更改颜色单元格1
和2
,这意味着仅在每个单元格中未设置背景色的情况下,颜色才会更改。
有什么方法吗?谢谢
$(function() {
$("td").click(function() {
$(this).css('background-color','yellow');
});
});
#aqua {
border-bottom: 3px solid aqua;
}
#green {
background-color:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<td id="1">1</td>
<td id="aqua">2</td>
<td id="green">3</td>
</table>
您可以添加将赋予其background:yellow
样式的类。这样,每当id给它其他任何颜色时,id选择器样式都会获得优先级,尽管该类是;
$(function() {
$("td").click(function() {
$(this).addClass('default-yellow');
});
});
#aqua {
border-bottom: 3px solid aqua;
}
#green {
background-color:green;
}
.default-yellow {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<td id="1">1</td>
<td id="aqua">2</td>
<td id="green">3</td>
</table>
在click事件处理程序中,首先检查元素上是否设置了任何颜色,并仅在不符合所需条件时才更改颜色。您可以使用$(this).css('background-color')
来获取当前颜色。
$(function() {
$("td").click(function() {
if ($(this).css('background-color') === 'rgba(0, 0, 0, 0)') {
$(this).css('background-color', 'yellow')
}
});
});
#aqua {
border-bottom: 3px solid aqua;
}
#green {
background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<td id="1">1</td>
<td id="aqua">2</td>
<td id="green">3</td>
</table>
$(function() {
$("td").click(function() {
$(this).addClass('test');
});
});
#aqua {
border-bottom: 3px solid aqua;
}
#green {
background-color:green;
}
.test{background:yellow;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<td id="1">1</td>
<td id="aqua">2</td>
<td id="green">3</td>
</table>