根据所选下拉菜单设置td单元的背景色

时间:2018-10-11 12:58:40

标签: jquery css

我拥有的代码:

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

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

3 个答案:

答案 0 :(得分:2)

尝试jquery正常工作

$('.green').on('change', function() {
  $(this).parent().css('background', $(this).val());
});
table tr td {
  padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <select class="green">
        <option value=""></option>
        <option value="yellow" style="background-color:yellow">One</option>
        <option value="red" style="background-color:red">Two</option>
        <option value="green" style="background-color:green">Three</option>
      </select>
    </td>
  </tr>
</table>

答案 1 :(得分:2)

您已将颜色应用于选择元素。而是应将其应用于select元素的父级。我在javascript中添加了.parentNode。

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>

答案 2 :(得分:1)

使用 jQuery 来捕获onchange选择事件。

然后,您可以使用select获取.parent()容器(它返回调用它的容器的父元素),并使用选定的值select设置其背景颜色。 / p>

$('select.color-select').change(function(){
  $(this).parent().css({ 'background-color': $(this).val() });
});
td {
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<select class="green color-select">
        <option value="" selected>Select a color</option>
        <option value="yellow" style="background-color:yellow">One</option>
        <option value="red" style="background-color:red">Two</option>
        <option value="green" style="background-color:green">Three</option> 
</select>
</td>
</tr>
</table>