javascript - 如何在选择某个选项时显示文本

标签 javascript html

我现在有点被某些事情困住了。我想让当用户从选择下拉表单中选择某个选项时显示带有文本的 DIV。这如何在 JavaScript 中完成?我在网上找到的内容仅采用您选择的内容并显示您选择的值。

然而,我想做这样的事情:

<select>
<option>One</option>
<option>Two</option>
</select>

<div id="text" style="display:hidden;">The text would show if the user chooses option "Two"</div>

有人知道怎么做吗?

更新:

这是我的问题。我现在尝试在正文和标题中使用此脚本:

<script type="text/javascript">
document.getElementById('script-choose').onchange=function(){
for(var i=0;i<document.getElementsByClassName('option-show').length;i++){
    document.getElementsByClassName('option-show')[i].style.display='none';
}
document.getElementById(document.getElementById('script-choose').value == 'gold').style.display='block';}
</script>

我的选择表单的 ID 是“script-choose”,我用来显示隐藏文本的值是“gold”。无论我何时选择“黄金”值,它都不会显示文本。这是我正在使用的 DIV:

<div id="one-show" class="option-show" style="font-size:10.5px;color:red;">You will get one free theme of choice later on! :D </div>

最佳答案

根据评论,您希望在选择“Two”时显示 div。为了清楚起见,以下是从开始到结束的完整代码:

<select id="mySelect" onchange='on_change(this)'> // Note the onchange event handler, which passes the select object to the on_change function via the 'this' variable
    <option value='one'>One</option> // Note I added value='one'
    <option value='two'>Two</option> // Note I added value='two'
</select>

<div id="text" style="display:none;"> // Note display:none instead of display:hidden
    The text would show if the user chooses option "Two"
</div>

<script>
    function on_change(el){
        if(el.options[el.selectedIndex].value == 'two'){ 
            document.getElementById('text').style.display = 'block'; // Show el
        }else{
            document.getElementById('text').style.display = 'none'; // Hide el
        }
    }
</script>

要回答您的问题,您不需要将 el 替换为 select 对象,该对象是在调用 on_change() 时使用 this 传递的 code> 在选择框 onChange 事件处理程序中。

此外,不要采纳这里基本上所有其他答案的建议。导入 jQuery 来执行像设置事件处理程序和操作 DOM 这样简单的事情是过度且毫无意义的 - 在学习 jQuery 之前先学习 JavaScript。

关于javascript - 如何在选择某个选项时显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18437761/

相关文章:

javascript - 将数据库数据加载到 javascript 文件中

JavaScript 库/框架从参数生成 XHTML?

html - 如何设置谷歌地图标记信息窗口的最大高度?

html - 参数和变量必须位于模板的顶部吗?

php - 我如何编写用于自动变色的 php 代码?

javascript - 如何动态更改数组中对象属性的键名

javascript - Node Selenium WebdriverJS - 如何检查元素是否真正可点击?

javascript - 根据词尾数组过滤单词数组

javascript - 视差背景没有正确排列

javascript - 为什么我无法注入(inject)我的服务?