仅在未在HTML表格中设置背景的情况下,如何更改背景颜色

问题描述 投票:1回答:3

下表具有某些类型的类。我想通过单击更改颜色单元格12,这意味着仅在每个单元格中未设置背景色的情况下,颜色才会更改。

有什么方法吗?谢谢

$(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>
javascript jquery html css html-table
3个回答
4
投票

您可以添加将赋予其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>

2
投票

在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>

1
投票

$(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>
© www.soinside.com 2019 - 2024. All rights reserved.