我试图更改选择元素中所选选项在下拉菜单中以及在主窗口中显示时的颜色。到目前为止,我已经能够更改所有选项的颜色。
<select id="drop-down" onchange="colorChange(event);">
<option value="">--</option>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
<option value="four">four</option>
</select>
这是我正在使用的功能。
var one = "one";
var two = "two";
var three = "three";
var four = "four";
function colorChange(event){
if(event.target.value == one){
event.target.style.color = "#67D986";
} else if (event.target.value == two || three || four){
event.target.style.color = "#f00";
} else{
alert("There has been an error!!!");
}
};
最佳答案
OR
条件中的 else if
存在问题,要在 OR
中添加条件,请使用以下内容
} else if (event.target.value == two || event.target.value == three || event.target.value == four) {
var colors = {
one: '#67D986',
two: '#f00',
three: '#f00',
four: '#f00'
};
$('#drop-down').on('change', function(e) {
var value = $('option:selected').val();
$('option').css('color', '#000');
if (!value) {
alert("There has been an error!!!");
} else {
$('option:selected').css('color', colors[value]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<select id="drop-down">
<option value="">--</option>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
<option value="four">four</option>
</select>
关于javascript - 更改选择元素中选项的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32139216/