Javascript:如果选择了选项,则更改选择背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22425421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:08:19  来源:igfitidea点击:

Javascript: Change select background-color if option is selected

javascripthtmlcss

提问by

I'm searching a while for a Javascript function that changes the background-color of my select field if an option is selected.

我正在搜索一个 Javascript 函数,如果选择了一个选项,它会更改我的选择字段的背景颜色。

HTML:

HTML:

<select name="classNumber" id="classNumber">
 <option selected disabled value="0">Bitte Klasse ausw?hlen</option>
 <option value="5">5</option>
 <option value="6">6</option>
 <option value="7">7</option>
 <option value="8">8</option>
 <option value="9">9</option>
 <option value="10">10</option>
 <option value="11">11</option>
 <option value="12">12</option>
 <option value="13">13</option>
</select>
<select name="classSpecify" id="classSpecify">
 <option selected disabled value="0">Bitte Klasse spezifizieren</option>
 <option value="A">A</option>
 <option value="B">B</option>
 <option value="D">C</option>
 <option value="D">D</option>
 <option value="N">N (Naturwissenschaftliches Profil)</option>
 <option value="S">S (Sprachliches Profil)</option>
 <option value="G">G (Gesellschaftliches Profil)</option>
</select>

Javascript that is not working, at this time just for testing I set up just one select:

无法运行的 Javascript,此时仅用于测试我只设置了一个选择:

var classNumber = document.getElementById('classNumber');
var first = classNumber.options[classNumber.selectedIndex].value;
if (first != 0) {
    alert('Test');
    document.getElementById('classNumber').style.background="$green";
};

采纳答案by galitskyd

I'm assuming you want to stay away from jQuery.

我假设您想远离 jQuery。

You are missing a few things. First off there is nothing that calling your if statement when a user CHANGESthe select. Add an event .onchange to classNumber as well as background to backgroundcolor.

你缺少一些东西。首先,当用户更改选择时,没有什么可以调用您的 if 语句。将事件 .onchange 添加到 classNumber 以及将 background 添​​加到 backgroundcolor。

Like so.

像这样。

var classNumber = document.getElementById('classNumber');
classNumber.onchange = runBackgroundChange;

function runBackgroundChange(first){
    var value = first.srcElement.options[first.srcElement.selectedIndex].value;
    if (value != 0) {
        alert('Test');
        document.getElementById('classNumber').style.backgroundColor="green";
    } else {
        document.getElementById('classNumber').style.backgroundColor="initial";
    };
}

回答by 13ruce1337

change this:

改变这个:

if (first != 0) {

if (first != 0) {

to:

到:

if (first !== 0) {

if (first !== 0) {

and this:

还有这个:

"$green"

"$green"

to:

到:

"green"

"green"

you want the comparison(==) operator.

你想要比较(==)运算符。