gpt4 book ai didi

javascript - 显示选择数据

转载 作者:行者123 更新时间:2023-11-28 13:03:59 25 4
gpt4 key购买 nike

我开始学习 DOM,我只是想测试一些东西,我创建了下拉列表,我想根据选择显示数据。我不知道我写的对不对。

提前感谢您的帮助。

var show = document.getElementById("show");
var select = document.getElementById("select");
if(select == "Boots"){
var newContent = document.createTextNode("You selected Boots");
show.appendChild(newContent);
}
else if(select == "Socks"){
var newContent2 = document.createTextNode("You selected Socks");
show.appendChild(newContent2);
}
else{
var newContent2 = document.createTextNode("You selected Tie");
show.appendChild(newContent2);
}
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
</head>
<body>
<div class="container">
<p class="lead">Please Choose one in the following</p>
<form>
<select class="custom-select" id="select">
<option class="active">Choose one...</option>
<option>Boots</option>
<option>Socks</option>
<option>tie</option>
</select>
</form><br>
<p id="show" class="lead">

</p>
</div>
</body>

最佳答案

您需要将代码包装在 onchange 事件处理程序中,以便每次选择更改时您的代码都会运行。这样就不需要在每次选择更改时都添加子节点,只需设置 show 元素的 innerHTML 即可。另外,除非您认为“tie”是默认值,否则您可能需要检查:

然后你需要正确获取所选项目的值。一种方法是执行 select.options[select.selectedIndex].text ,它将获取所选 option 元素的文本值。

var show = document.getElementById("show");
var select = document.getElementById("select");

select.onchange = function(){
value = select.options[select.selectedIndex].text;
if(value == "Boots"){
show.innerHTML = "You selected Boots";
}
else if(value == "Socks"){
show.innerHTML = "You selected Socks";
}
else if(value == "tie"){
show.innerHTML = "You selected Tie";
}
else {
show.innerHTML = "";
}
}
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
</head>
<body>
<div class="container">
<p class="lead">Please Choose one in the following</p>
<form>
<select class="custom-select" id="select">
<option class="active">Choose one...</option>
<option>Boots</option>
<option>Socks</option>
<option>tie</option>
</select>
</form><br>
<p id="show" class="lead">

</p>
</div>
</body>

关于javascript - 显示选择数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48071412/

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