2010-03-09 56 views
1

我想在javascript中切换表格的显示行。我该怎么做呢?如何循环显示表格行来切换显示样式?

<script type="text/javascript" language="javascript"> 
     function vehicleSelected() { 
      var autoSelect = document.getElementById('vehicleSelect'); 
      var strAuto = autoSelect.options[autoSelect.selectedIndex].value;         
      var rowAuto = document.getElementById(strAuto);    
      for (var i = 4; i < tableList.rows.length; i++) { 
       //I am not sure how to access the id for comparison to rowAuto      
       if (//table row == strAuto) { 
        rowAuto.style.display = ''; 
       } else { 
        rowAuto.style.display = 'none'; 
       } 
      } 
     }  
    </script> 
<table id="tableList"> 
    <tr id="optionA"><td>Display Row A</td></tr> 
    <tr id="optionB"><td>Display Row B</td></tr> 
    <tr id="optionC"><td>Display Row C</td></tr> 
    <tr id="optionD"><td>Display Row D</td></tr> 
</table> 

回答

3

首先,考虑jQuery。这对这样的事情有很大的帮助。

其次,如果你不打算使用jquery,然后你想做的事是这样的:

function vehicleSelected() { 
     var autoSelect = document.getElementById('vehicleSelect'); 
     var strAuto = autoSelect.options[autoSelect.selectedIndex].value;         
     var rows = document.getElementById('tableList').getElementsByClassName('TR');    
     for (var i = 0; i < rows.length; i++) {  
      rows[i].style.display='none'; // note: better to use a css class here 
     } 
     var selectedRow = document.getElementById(strAuto); // assuming that the values are the same as the row Id's. 
     selectedRow.style.display = ''; // again, better to use a Css style. 
    } 
+0

+1使用jQuery – 2010-03-09 20:49:50

1

你可以用jQuery轻松地做到这一点:

function vehicleSelected() { 
    var autoSelect = //... 
    var strAuto = //... 

    $("#tableList tr").hide().filter("#" + strAuto).show(); 
} 
1

如果我correctry了解你,这应该帮助你。

var table = document.getElementById('tableList'); 
for(var i=0; i<table.rows.length; i++){ 
    if (table.rows[i].attributes["id"].nodeValue == strAuto) { 
     table.rows[i].style.display = ''; 
    } else { 
     table.rows[i].style.display = 'none'; 
    } 
}