gpt4 book ai didi

javascript - JS根据所选选项切换

转载 作者:行者123 更新时间:2023-12-02 15:32:55 27 4
gpt4 key购买 nike


我尝试编写简单的 JS 开关,它将根据选择显示内容,所以假设我将拥有包含 4 个 div 的 html 文档,如果用户选择选项第一个 div,将显示第一个选项等。

这是我制作的快速草稿,但它不起作用。你能帮我理解我在这里做错了什么吗?

HTML

  <legend>Selecting elements</legend>
<p>
<label>Select list</label>
<select id = "myList">
<option value = "1">one</option>
<option value = "2">two</option>
<option value = "3">three</option>
<option value = "4">four</option>
</select>
</p>
</fieldset>
<p id ="demo"></p>


JS

function myfunction () {
var text;
var city = getElementById("myList").value;

switch(city) {
case "one":
text ="test one";
break;

case "two":
text ="test two";
break;

case "three":
text ="test three";
break;

case "four":
text = "test four";
break;

default:
text = " ";
}
document.getElementById("demo").innerHTML = text;
}

最佳答案

代码有一些问题

function myfunction() {
var text;
var city = document.getElementById("myList").value; //need to use document.getElementById()

switch (city) {
//the select values are 1, 2, 3 not one, two etc
case "1":
text = "test one";
break;

case "2":
text = "test two";
break;

case "3":
text = "test three";
break;

case "4":
text = "test four";
break;

default:
text = " ";
}
document.getElementById("demo").innerHTML = text;
}
<legend>Selecting elements</legend>
<p>
<label>Select list</label>
<!--Need to call myfunction on change of the select-->
<select id="myList" onchange="myfunction()">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
</p>
</fieldset>
<p id="demo"></p>

<小时/>

如果您只想显示预定义的文本,那么

var mymap = {
1: "test one",
2: 'test two',
3: 'test three',
4: 'test four'
}

function myfunction() {
var city = document.getElementById("myList").value; //need to use document.getElementById()
var text = mymap[city] || ' ';
document.getElementById("demo").innerHTML = text;
}
<legend>Selecting elements</legend>
<p>
<label>Select list</label>
<!--Need to call myfunction on change of the select-->
<select id="myList" onchange="myfunction()">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
</p>
</fieldset>
<p id="demo"></p>

关于javascript - JS根据所选选项切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33166003/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com