如何在 HTML 中使用带有 select 标签的 if 语句 (JavaScript)?

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

How to use the if statement (JavaScript) with the select tag in HTML?

javascripthtml

提问by Christian Landgren

I've tried many ways to do this but this isn't right:

我已经尝试了很多方法来做到这一点,但这是不对的:

<html>
    <head>
        <title>Select</title>
    </head>
    <body>
        <select name="test">
            <option value="one">1</option>
            <option value="two">2</option>
            <option value="three">3</option>
        </select>
        <script>
        if (test=="two") {
            document.write("two!");
        }
        </script>
    </body>
</html>

I want to let something appear on the screen if the user chooses "two" but this doesn't work.

如果用户选择“两个”,我想让一些东西出现在屏幕上,但这不起作用。

回答by urfusion

I think this might help you

我想这可能对你有帮助

<select name="test" id="mySelect" onchange="myFunction()">
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>

<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementById("mySelect").value;
    if(x == "two"){
       document.getElementById("demo").innerHTML = "You selected: " + x;
    }
}
</script>

Have a look http://jsfiddle.net/snsbbytw/

看看 http://jsfiddle.net/snsbbytw/

回答by Stranded Kid

I guess you have to listen to the change event of the select.

我猜你必须听选择的更改事件。

document.getElementsByName("test")[0].addEventListener("change", function(e) {
   if (e.target.value === "two") { // not sure if it's e.targe.value, and this might not work in all browsers
       document.write("two!");
   }
}

回答by Christian Landgren

You are probably looking for the onChange event

您可能正在寻找 onChange 事件

<select name="test" onchange="console.log(this.value)">

Avoid using document.write since it will replace the document output.. And of course, avoid use inline scripting ;)

避免使用 document.write 因为它会替换文档输出.. 当然,避免使用内联脚本 ;)