Html选择选项更改颜色文本


Html select option change color text

A有一个名为Systems(id, name)的表。我发送了一个查询SELECT * FROM Systems WHERE id = SPECIFIC_ID。然后我有另一个查询SELECT * FROM Systems WHERE id != SPECIFIC_ID

我把它们都显示在一个html选择中,如下所示:

<select id="select">
<option value="'.$row1["id"].'">'.$row1["name"].'</option> // this is the result of the first query
while () {
    //the result of the second query
}
</select>

现在我想让第一个选项变成红色。现在我尝试使用我在stackoverlow:上找到的jQuery代码

$(document).ready(function() {
    $('#select').css('color','gray');
    $('#select').change(function() {
       var current = $('#select').val();
       if (current != 'null') {
           $('#select').css('color','black');
       } else {
           $('#select').css('color','gray');
       }
    }); 
});

上面的代码就是这样工作的:http://jsfiddle.net/fMQeq/

但要使用它,您需要有一个特定的值。在我的情况下,这个值不是静态的。如何为该选项上色?

选项标签本身不能在其上设置样式。

但你可以对这个目标采取另一种方法:

只需制作一个包含所有option元素的下拉div,并为其设置点击事件,点击后更改<select>标记值。然后隐藏<select>标签。

你能举个例子吗?

    <style>
    .gray{
        background-color:#f00;
        border:2px solid #f00;
        color:#f00;
    }
    .black{
        background-color:#000;
        border:2px solid #000;
    }
    </style>

HTML

    <select id="select">
    <option value="">--Select --</option> // this is the result of the first query
    <option value="1">One</option> // this is the result of the first query
    </select>

脚本

    <script>
    $(document).ready(function() {
        $('#select').attr('color','gray');
        $('#select').change(function() {
           var current = $('#select').val();
           if (current == "") {
               $('#select').attr('class','black');
           } else {
               $('#select').attr('class','gray');
           }
        }); 
    });
    </script>

使用原始css

select:nth-child(1){
    color:red;
}

您不需要将ID放在那里

您可以这样做:)将css代码直接放在html中并非不可能。

<p><a href="http://www.korben.info/42" style="font-size:10px"><font color="red">YEAH</font></a>