javascript - 将所选值从 <select> HTML 标记传递到 JAVASCRIPT

标签 javascript html

如何获取 <select> 的值在我的 html 中标记并将其传递到我的 javascript。

当我选择 red 时它应该显示我的 <div id="red"> 我是 JS 的新手,所以我不确定我的语法是否正确。

HTML

<select>
<option name="choice1" value="red" onclick="color(this.value)">red</option>
<option name="choice2" value="blue" onclick="color(this.value)">blue</option>
</select>

<div id="red" style="display:none;">
<p>You want RED</p>
</div>

<div id="blue" style="display:none;">
<p>You want BLUE</p>
</div>

JavaScript

function color(color_type){
if (color_type == 'blue'){
document.getElementById('blue').style.display = 'block';
document.getElementById('red').style.display = 'none';
} 
else{
document.getElementById('blue').style.display = 'none';
document.getElementById('red').style.display = 'block';
}
}

最佳答案

你应该使用onchange事件而不是onclick,此外,事件应该设置为select而不是option 以下是正确的代码

<script>
function color(color_type){
    if (color_type == 'blue'){
        document.getElementById('blue').style.display = 'block';
        document.getElementById('red').style.display = 'none';
    } 
    else{
        document.getElementById('blue').style.display = 'none';
        document.getElementById('red').style.display = 'block';
    }
}
</script>

<select onchange="color(this.value)">
    <option name="choice1" value="red" >red</option>
    <option name="choice2" value="blue" >blue</option>
</select>

<div id="red" style="display:none;">
    <p>You want RED</p>
</div>

<div id="blue" style="display:none;">
    <p>You want BLUE</p>
</div>

希望有帮助!

关于javascript - 将所选值从 <select> HTML 标记传递到 JAVASCRIPT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18055947/

相关文章:

javascript - Bootstrap 3 : how to set the list to expand

javascript - 使用 js jQuery 的 Rails 3.1 错误 - "Template is missing"

javascript - 在 Angular ng-show 中使用类似 linq 的表达式

javascript - 展开和折叠 div

php - 从服务器目录填充选择 PHP jQuery AJAX

javascript - 如何在 Kendo-UI 中绘制条形图的连接线

html - 悬停时如何显示文字?

javascript - 从主干集合中获取每个模型

Html 到 FOP 与 XSLT : css class to attribute-set

html - 使用负边距使 block 级元素位于其内容区域之外