简体   繁体   English

显示/隐藏使用下拉列表

[英]Show/Hide using drop down list

Hello I am trying to use this code below. 您好,我正在尝试使用以下代码。 I like the code but I want the default to be DIV Area 1. I have the HTML code showing DIV Area 1 in the drop down menu but I want the Javascript to show DIV AREA 1 by default. 我喜欢该代码,但我希望默认值为DIV Area1。在下拉菜单中有显示DIV Area 1的HTML代码,但我希望Javascript默认显示DIV Area 1。 What would be the code? 代码是什么?

    <script type="text/javascript">
    $(document).ready(function(){
        $('.box').hide();
        $('#dropdown').change(function() {
            $('.box').hide();
            $('#div' + $('#dropdown').val()).show();
        });
    });
</script>

<form>
    <select id="dropdown" name="dropdown">
     <option value="0">Choose</option>
     <option value="area1" selected="selected">DIV Area 1</option>
     <option value="area2">DIV Area 2</option>
     <option value="area3">DIV Area 3</option>
    </select>
</form>

<div id="divarea1" class="box">DIV Area 1</div>
<div id="divarea2" class="box">DIV Area 2</div>
<div id="divarea3" class="box">DIV Area 3</div>
$('.box').hide().first().show();

Or: 要么:

$('.box').hide().filter("#divarea1").show(); 

Live DEMO 现场演示

Put one of the above in the DOM ready event: 将以上内容之一放入DOM ready事件:

$(function(){ /*...*/ });

Or 要么

$(document).ready(function(){ /* ... */ });

Full code: (It should answer you next question regarding how to show the selected div...) 完整代码:(它应该回答您有关如何显示所选格的下一个问题...)

$(document).ready(function() {

    $('.box').hide().filter("#divarea1").show();

    $('#dropdown').change(function() {
        var selectedId= $(this).find(':selected').text().replace(/\s/g, "").toLowerCase();
        console.log(selectedId);
        $('.box').hide().filter('#' + selectedId).show();
    });
});​

可以做到...

$('.box').hide().filter(':first').show();

A lot of complicated answers for a simple problem: 对于一个简单的问题有很多复杂的答案:

$('.box:gt(0)').hide();

I'd code it up like this: 我会这样编码:

 $(document).ready(function(){
     $('.box:gt(0)').hide();

    $('#dropdown').change(function() {
        $('.box:visible').hide();
        if ($(this).prop('selectedIndex')>0)
            $('.box').eq($(this).prop('selectedIndex')-1).show();        
    });
});​

http://jsfiddle.net/lucuma/xNZWY/ http://jsfiddle.net/lucuma/xNZWY/

If you remove the 1st option from your dropdown (since you are preselecting is it necessary?) it becomes a little simpler since we can remove the if 如果您从下拉菜单中删除第一个选项(因为您已经进行了预选,是否有必要?),它会变得简单一些,因为我们可以删除if

$(document).ready(function(){
     $('.box:gt(0)').hide();

    $('#dropdown').change(function() {
        $('.box:visible').hide();
        $('.box').eq($(this).prop('selectedIndex')-1).show();        
    });
});​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM