2016-08-02 52 views
1

我使用Javascript在HTML表格列中搜索。但是,我只能通過輸入表格單元格內容的第一個字母來搜索值。用Jquery部分搜索TABLE中的單詞

我的數據示例如下所示。

如果我在柱2搜索的值,期望的表格單元格像它應該彈出。

如果我搜索的值或例如,沒有任何反應。

|column1|column2| 
__________________ 
|000|123 456| 
|001|123 456| 

我目前的Javascript:

<script type="text/javascript"> 
     $("#searchn").on("keyup", function() { 
      var value = $(this).val(); 

      $("table tr").each(function(index) { 
       if (index !== 0) { 

        $row = $(this); 

        var id = $row.find("td").children().eq(1).text(); 

        if (id.indexOf(value) !== 0) { 
         $row.hide(); 
        } 
        else { 
         $row.show(); 
        } 
       } 
      }); 
     }); 
     </script> 

回答

0

你的邏輯是有缺陷的indexOf()回報-1,如果你要搜索的值沒有找到,而本場比賽的從零開始的索引,如果它是找到。正因爲如此,您的if聲明有缺陷,因爲它排除了值的起始處的匹配。

你應該改變你的if條件,這個代替:

if (id.indexOf(value) !== -1) { 
    $row.hide(); 
} 
else { 
    $row.show(); 
} 

另外請注意,您可以縮短這個使用filter()toggle()代替:

$("#searchn").on("keyup", function() { 
 
    var value = $(this).val(); 
 

 
    $("table tr:not(:first)").show().filter(function(index) { 
 
     return $(this).find("td:eq(1)").text().indexOf(value) == -1; 
 
    }).hide(); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <tr> 
 
    <th>Col 1</th> 
 
    <th>Col 2</th> 
 
    </tr> 
 
    <tr> 
 
    <td>000</td> 
 
    <td>123 456</td> 
 
    </tr> 
 
    <tr> 
 
    <td>001</td> 
 
    <td>123 456</td> 
 
    </tr> 
 
</table> 
 

 
<input id="searchn" />

+0

工程就像一個魅力:)!謝謝你的解釋和明確的例子。 – Leon

+0

沒問題,很高興幫助 –