如何在HTML中使用if语句(JavaScript)和select标记

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

本文关键字:JavaScript 标记 select 语句 if HTML      更新时间:2023-09-26

我已经尝试了很多方法,但这是不对的:

<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>

我想让一些东西出现在屏幕上,如果用户选择" 2 ",但这不起作用

我想这可能对你有帮助

<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>

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

我猜你必须听select的change事件

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!");
   }
}

您可能正在寻找onChange事件

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

避免使用document。写入,因为它将替换文档输出。当然,避免使用内联脚本;)