2013-07-08 108 views
0

我有2個表格「iu」和「si」,並且我爲用戶設置了一個下拉列表以選擇他們想要查看的表格。一旦選擇了該選項,相應的表格就會出現。選擇不同選項後隱藏/顯示錶格

另一個應該是隱藏的,但是當頁面加載時,顯示默認表「si」。

這裏是我的JavaScript代碼:

<script> 
    $(document).ready(function() 
    { 
     $('#iu_table').hide(); 
    }); 
    $('#iu').onchange=function() 
    { 
     $('#si_table').hide(); 
     $('#iu_table').toggle(); 
    } 
</script> 

和HTML代碼:

<select> 
     <option id="si" selected>SI</option> 
     <option id="iu">IU</option> 
    </select> 

表ID分別是 「si_table」 和 「ui_table」。

我使用了上面的代碼,但它不起作用。無論選擇哪一個,只顯示「si」表格。

我希望有人能幫忙。

+0

請參閱此鏈接可以幫助ühttp://stackoverflow.com/questions/1240205/how-to-hide-show-select-boxes-depending-on-other-choosed-select-box-選項 – Bharu

回答

1

你或許應該使用jQuery的教程工作,並與圖書館的運作familarize自己。

有在你的代碼的多個錯誤:

  • 沒有電平變化領域。你需要的是jQuery的更改功能,這裏描述如下:http://api.jquery.com/change/
  • 更改函數的代碼屬於$(document).ready函數,所以jquery在加載文檔時執行它。該代碼必須在那裏執行,以便在更改選擇時調用該函數。
  • 您想要改變選擇而不是改變選項。
  • 在更改功能的主體中,您隱藏了一個表格並切換其他:切換兩者,因此當選擇該選項時,也可以顯示第一個。這個構造也只適用於2個選項。如果你想要更多的選擇,你必須像Paritosh的答案一樣工作。

這裏是工作示例:

<html> 
<head> 
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script> 
<script> 
    $(document).ready(function() 
    { 
     $('#iu_table').hide(); 
     $('#selector').change(function() 
      { 
       $('#si_table').toggle(); 
       $('#iu_table').toggle(); 
      }); 
    }); 

</script> 
</head> 
<body> 
<div id="si_table">si</div> 
<div id="iu_table">iu</div> 
<select id="selector"> 
     <option id="si" selected="selected">SI</option> 
     <option id="iu">IU</option> 
</select> 
</body> 
+0

非常感謝!我是一個javascript新手..這是我第一次使用js ..我將在未來遵循jquery教程和研究。感謝您的批評和解決方案。大聲笑.. =) – Hongxuan

+0

但是,如果有3個或更多的表... – Hongxuan

+0

,這種方式似乎無效,如我在最後一個要點中所述。 – Silahe

1

有很多方法來實現這一點。一個是下面 - 我加入id屬性下拉控件

<select id="myselection"> 
    <option id="si" selected>SI</option> 
    <option id="iu">IU</option> 
</select> 

<script> 
$('#myselection').bind('change', function(){ 
    if($('#myselection option:selected').attr('id') == "si"){ 
     $('#si_table').show(); 
     $('#iu_table').hide(); 
    } 
    else if($('#myselection option:selected').attr('id') == "iu"){ 
     $('#si_table').hide(); 
     $('#iu_table').show(); 
    } 
}); 
</script> 
1

有jQuery中的方法,它確實隱藏/顯示匹配的元素稱爲toggle() 當你需要隱藏在第一IU表,你可能需要一些css技巧。因此,將display:none;放在IU表中,並切換改變下拉值。工作小提琴是here