使用下拉列表显示/隐藏

您好我正在尝试使用下面的代码。 我喜欢这些代码,但我希望默认为DIV Area 1.我在下拉菜单中显示了DIV Area 1的HTML代码,但我希望Javascript默认显示DIV AREA 1。 代码是什么?

 $(document).ready(function(){ $('.box').hide(); $('#dropdown').change(function() { $('.box').hide(); $('#div' + $('#dropdown').val()).show(); }); });  
Choose DIV Area 1 DIV Area 2 DIV Area 3
DIV Area 1
DIV Area 2
DIV Area 3

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

要么:

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

现场演示

将上面的一个放在DOM ready事件中:

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

要么

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

完整代码:(它应该回答你关于如何显示所选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();

一个简单问题的许多复杂答案:

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

我会像这样编码:

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