Html 如果选择了选项,则运行 javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18303740/
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-08-29 12:17:29  来源:igfitidea点击:

Run javascript function if option selected

javascripthtmlsyntax-errorhtml-select

提问by crazyim5

If I have a select like this

如果我有这样的选择

<select id="selectid" name="selectname" onchange="jsfunc1()">
    <option value="val1" id="valid1"> Val1 </option>
    <option value="val2" id="valid2"> Val2 </option>
    <option value="val3" id="valid3"> Val3 </option>
</select>

I now have a javascript function func2, say, that need to do something if option val1is selected. How do I do that?

我现在有一个 javascript 函数func2,比如说,如果选择了选项,它需要做一些事情val1。我怎么做?

For example,

例如,

function func2(){
    ....
    if(document.getElementById('valid2').selected==True){
        //Do something 
    }
}

I'm not getting the exact syntax right and that's where I need your help.

我没有得到正确的语法,这就是我需要你的帮助的地方。

回答by Krasimir

I guess that this will work for you.

我想这对你有用。

if(document.getElementById('selectid').value == "val1") {
     //Do something
}