首页 > 解决方案 > 根据选定的下拉菜单设置 td 单元格的背景颜色

问题描述

我的代码:

<table>
  <tr>
    <td>
      <select onchange="this.style.backgroundColor=this.options[this.selectedIndex].style.backgroundColor">
        <option value=""></option>
        <option value="1" style="background-color:yellow">One</option>
        <option value="2" style="background-color:red">Two</option>
        <option value="3" style="background-color:green">Three</option>
      </select>
    </td>
  </tr>
</table>

现在在这里我可以在下拉框中设置选项的背景颜色。我需要的是使用选定的选项颜色设置单元格的背景颜色。我在互联网上搜索了很多,但找不到类似的东西。小提琴

标签: jquerycss

解决方案


您将颜色应用于选择元素。相反,您应该将其应用于 select 元素的父级。我将 .parentNode 添加到 javascript 中。

td {
padding: 1rem; /* Just to make the color better visible */
}
<table>
  <tr>
    <td>
      <select onchange="this.parentNode.style.backgroundColor=this.options[this.selectedIndex].style.backgroundColor;this.style.backgroundColor=this.options[this.selectedIndex].style.backgroundColor">
        <option value=""></option>
        <option value="1" style="background-color:yellow">One</option>
        <option value="2" style="background-color:red">Two</option>
        <option value="3" style="background-color:green">Three</option>
      </select>
    </td>
  </tr>
</table>


推荐阅读