代码之家  ›  专栏  ›  技术社区  ›  Max

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

  •  1
  • Max  · 技术社区  · 6 年前

    <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 回复  |  直到 6 年前
        1
  •  2
  •   Gerard    6 年前

    您将颜色应用于select元素。相反,应该将其应用于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
  •  2
  •   Bhargav Chudasama    6 年前

    尝试 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>
        3
  •  1
  •   Marco Dal Zovo    6 年前

    jQuery查询 抓住 onchange 选择事件。

    然后,你就可以 select 容器使用 .parent() (它返回调用它的元素的父元素)并用所选值设置其背景色 选择

    $('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>