2012-06-05 39 views
0

您好,我正在嘗試使用下面的代碼。我喜歡代碼,但我希望默認設置爲DIV區域1.我的HTML代碼在下拉菜單中顯示DIV區域1,但我希望JavaScript在默認情況下顯示DIV AREA 1。代碼是什麼?顯示/隱藏使用下拉列表

<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> 

回答

5
$('.box').hide().first().show(); 

或者:

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

Live DEMO

把上面的一個在DOM ready事件:

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

或者

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

全碼:(它應該回答你關於如何顯示所選格下一個問題......)

$(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(); 
    }); 
});​ 
+0

這正是我一直在尋找的感謝 –

+0

@ G-呦。看到我的更新爲您的下一個問題... :) – gdoron

1

能做到這一點...

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

+0

我確定'.filter(':第一')'是一個非常非常緩慢的過濾方式。想想爲了知道'first'是什麼而需要採取的行動! – gdoron

+0

是的,你的效率可能更高 –

0

一個簡單的問題很多複雜的答案:

如果您從下拉列表中刪除第一個選項(因爲你是預選有必要嗎?)

$(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/

就顯得有點簡單:

我想它這樣的代碼了因爲我們可以刪除if

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

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