如何根据下拉选项隐藏和显示内容 [英] How to hide and show content based on drop down selection

查看:151
本文介绍了如何根据下拉选项隐藏和显示内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想隐藏并根据下拉选项显示div。也就是说,如果我选择下拉选项1,则应显示id为1的div,以及id为2的2 div,依此类推。但我想这样做而不使用jQuery但使用css或Javascript。这可能吗?继承我的样品下拉。谢谢你们。

I want to hide and show a div based on a drop down selection. That is if I select drop down option 1, div with the id 1 should show up, and for 2 div with id 2 and so on. But I want to do this without using jQuery but with css or Javascript. Is this possible? Heres my sample drop down. Thanks guys.

<select name="options">
  <option value="1"> Loan Protection Insurance</option>
  <option value="2"> GAP or Cash Assist Insurance</option>
  <option value="3"> Home Insurance</option>
  <option value="4"> Landlords Insurance</option>
  <option value="5">  Car Insurance</option>
</select>

<div id="1">Test</div>
<div id="2">Test</div>


推荐答案

单独使用CSS是不可能的,因为你需要处理更改下拉事件并采取相应措施。

Not possible with CSS alone as you need to handle the change event of the drop down and take appropriate action.

您可以通过纯JS轻松完成:

You can do it easily via pure JS:

document.getElementById('id-of-select').onchange = function() {
    var i = 1;
    var myDiv = document.getElementById(i);
    while(myDiv) {
        myDiv.style.display = 'none';
        myDiv = document.getElementById(++i);
    }
    document.getElementById(this.value).style.display = 'block';
};

演示: http://jsfiddle.net/2ukyA/

更新:如果DIV的ID类似于divname1等。

Update: If IDs of the DIVs are like "divname1" etc..

document.getElementById('id-of-select').onchange = function() {
    var i = 1;
    var myDiv = document.getElementById("divname" + i);
    while(myDiv) {
        myDiv.style.display = 'none';
        myDiv = document.getElementById("divname" + ++i);
    }
    document.getElementById(this.value).style.display = 'block';
};

这篇关于如何根据下拉选项隐藏和显示内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆