首页 > 解决方案 > thymeleaf 选择背景颜色

问题描述

我有以下 HTML:

<select  
        th:field="*{status.health}" 
        th:value="${status.health}"
        th:class="health_color"                                 
        th:name="status_health">
    <option value="-1">Select Health</option>
    <option th:class="health_color" th:value="green" th:text="green"></option>
    <option th:class="health_color" th:value="yellow" th:text="yellow"></option>
    <option th:class="health_color" th:value="red" th:text="red"></option>
</select>

以及下面的 JavaScript

$('.health_color').each(function() {
    if ($(this).text() == 'red') {
        $(this).css('background-color', '#ff5050');
    } else if ($(this).text() == 'yellow') {
        $(this).css('background-color', '#ffd24d')
    } else if ($(this).text() == 'green') {
        $(this).css('background-color', '#80ffaa')
    }
});

上面的样式显示在页面的所有其他元素中,包括选择选项,但不显示选择框本身。我究竟做错了什么?

谢谢。

标签: htmlcssthymeleaf

解决方案


我相信该函数期望从该select字段没有的文本属性中读取颜色。

我最好的猜测是,当$(this).text()为 运行时select,它返回里面所有文本属性的组合属性。

下面是测试我的理论的代码片段。

请记住,您始终可以使用 chrome 开发人员工具(例如)调试您的代码,它可以让您更好地了解它发生了什么。

$('.health_color').each(function() {
    console.log($(this).text());
    if ($(this).text() == 'red') {
        $(this).css('background-color', '#ff5050');
    } else if ($(this).text() == 'yellow') {
        $(this).css('background-color', '#ffd24d')
    } else if ($(this).text() == 'green') {
        $(this).css('background-color', '#80ffaa')
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="health_color"                                 
        name="status_health">
    <option value="-1">Select Health</option>
    <option class="health_color" value="green" text="green">green</option>
    <option class="health_color" value="yellow" text="yellow">yellow</option>
    <option class="health_color" value="red" text="red">red</option>
</select>


推荐阅读