使用javascript根据选择显示/隐藏(切换)div的显示 [英] Show/hide (toggle) the display of divs based on selection using javascript

查看:115
本文介绍了使用javascript根据选择显示/隐藏(切换)div的显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有下拉菜单和两个div的网页,如下所示:

I have a web page with a dropdown menu and two divs as given below:

<html>
<head>
<title>Show/Hide a div section based on selection</title>
</head>
<body>
    <select id='sel'>
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    </select>

    <div id="firstdiv">
    <label><input type="checkbox" id='1' />A</label>
    <label><input type="checkbox" id='2' />B</label>
    <label><input type="checkbox" id='3' />C</label>
    </div>

    <div id="seconddiv">
    <label><input type="checkbox" id='4' />D</label>
    <label><input type="checkbox" id='5' />E</label>
    <label><input type="checkbox" id='6' />F</label>
    </div>
</body>
</html>

如何根据使用javascript或jQuery的选择切换上述两个div的显示?即当我选择选项1时,firstdiv应该显示,之后应该隐藏,反之亦然。

How can I toggle the display of the above two divs based on selection using javascript or jQuery? I.e. when I select option 1, the firstdiv should display and later one should hide and vice versa.

推荐答案

演示

HTML

<select id="selectMe">
    <option value="div1">div1</option>
    <option value="div2">div2</option>
</select>
<br><br><br>

 <div id="div1" class="group" >
  <label><input type="checkbox" id='1' />A</label>
<label><input type="checkbox" id='2' />B</label>
<label><input type="checkbox" id='3' />C</label>
</div>

 <div id="div2" class="group" >
  <label><input type="checkbox" id='4' />D</label>
<label><input type="checkbox" id='5' />E</label>
<label><input type="checkbox" id='6' />F</label>
</div>

JS:

$(document).ready(function () {
    $('.group').hide();
    $('#div1').show();
    $('#selectMe').change(function () {
        $('.group').hide();
        $('#'+$(this).val()).show();
    })
});

这篇关于使用javascript根据选择显示/隐藏(切换)div的显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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