代码之家  ›  专栏  ›  技术社区  ›  MrM

如何循环表行以切换显示样式?

  •  1
  • MrM  · 技术社区  · 14 年前

    我想用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 回复  |  直到 14 年前
        1
  •  3
  •   Paul    14 年前

    首先,考虑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.
        }
    
        2
  •  1
  •   bcherry    14 年前

    使用jquery可以很容易地做到这一点:

    function vehicleSelected() {
       var autoSelect = //...
       var strAuto = //...
    
       $("#tableList tr").hide().filter("#" + strAuto).show();
    }
    
        3
  •  1
  •   Zango    14 年前

    如果我能正确地理解你,这会对你有所帮助。

    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';
       }
    }