2014-06-27 92 views
0

的問題是如何執行表中的HTML TD表搜索

我用下面的JS腳本和輸入標籤的某列搜索:

<script type="text/javascript"> 
    function doSearch() { 
     var searchText = document.getElementById('searchTerm').value; 
     var targetTable = document.getElementById('dataTable'); 
     var targetTableColCount; 

     //Loop through table rows 
     for (var rowIndex = 0; rowIndex < targetTable.rows.length; rowIndex++) { 
      var rowData = ''; 

      //Get column count from header row 
      if (rowIndex == 0) { 
       targetTableColCount = targetTable.rows.item(rowIndex).cells.length; 
       continue; //do not execute further code for header row. 
      } 

      //Process data rows. (rowIndex >= 1) 
      for (var colIndex = 0; colIndex < targetTableColCount; colIndex++) { 
       var cellText = ''; 

       if (navigator.appName == 'Microsoft Internet Explorer') 
        cellText = targetTable.rows.item(rowIndex).cells.item(colIndex).innerText; 
       else 
        cellText = targetTable.rows.item(rowIndex).cells.item(colIndex).textContent; 

       rowData += cellText; 
      } 

      // Make search case insensitive. 
      rowData = rowData.toLowerCase(); 
      searchText = searchText.toLowerCase(); 

      //If search term is not found in row data 
      //then hide the row, else show 
      if (rowData.indexOf(searchText) == -1) 
       targetTable.rows.item(rowIndex).style.display = 'none'; 
      else 
       targetTable.rows.item(rowIndex).style.display = 'table-row'; 
     } 
    } 
</script> 

,我想修改該腳本只在搜索所需列

+0

提供表格html代碼。你是什​​麼意思的「某一欄」。預定的一個?或者用戶可以選擇列? –

+0

我想做幾個輸入來搜索每個預定的列,因爲表格很大,只使用一個搜索輸入會導致結果過度 – user3663497

回答

0

變化:

for (var colIndex = 0; colIndex < targetTableColCount; colIndex++) { 

要改爲使用一個特定的FIC列數:

if(colIndex<targetTableColCount) //Ensures the selected column exists 

要獲得colIndex數,你能與列名作爲文本和索引值下拉。

<option id="searchID" onchange="UpdateColIndex()"> 
<select value="0">Column 1</select> 
<select value="1">Column 2</select> 
</option> 
<script> 
var colIndex=0; 
function UpdateColIndex() 
{ 
    colIndex = document.getElementById("searchID").value; 
} 
</script>