首页 > 解决方案 > 通过 bgcolor 属性选择元素

问题描述

我想在其 CSS 包含特定背景颜色(bgcolor 属性)的表中选择一堆 td。我如何实现这一目标?

我试过$("[bgcolor=#FF0000]")了,但我得到了错误。Uncaught DOMException: Failed to execute '$' on 'CommandLineAPI': '[bgcolor=#FF0000]' is not a valid selector.

<table>
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td bgcolor="#FF0000">January</td>
    <td bgcolor="#00FF00">$100</td>
  </tr>
</table>

标签: jqueryjquery-selectors

解决方案


当您想按属性值查找元素时,选择器需要双引号。

$('[bgcolor="#FF0000"]').each(function(e){
	$(this).text('wow my bg is red');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td bgcolor="#FF0000">January</td>
    <td bgcolor="#00FF00">$100</td>
  </tr>
</table>


推荐阅读