[英]Table - Live Search with jQuery
我一直在為我的數據表上的實時搜索解決方案。
當我搜索Jim
它按預期工作:-)
但是,當我搜索Carey
,沒有結果出現。 為什么是這樣? :-(
演示: http : //jsfiddle.net/L1d7naem/
$("#search").on("keyup", function() { var value = $(this).val(); $("table tr").each(function(index) { if (index !== 0) { $row = $(this); var id = $row.find("td:first").text(); if (id.indexOf(value) !== 0) { $row.hide(); } else { $row.show(); } } }); });
table, tr, td, th{ border: 1px solid blue; padding: 2px; } table th{ background-color: #999999; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr><th>Forename</th><th>Surname</th><th>Extension</th></tr> <tr><td>Jim</td><td>Carey</td><td>1945</td></tr> <tr><td>Michael</td><td>Johnson</td><td>1946</td></tr> </table> <br /> <input type="text" id="search" placeholder=" live search"></input>
因為以下幾行:
var id = $row.find("td:first").text();
您正在處理表的第一列,而“Carey”位於表的第二列
您可以通過每個循環中的以下更正來實現您想要的行為(還要注意條件中的< 0
):
var id = $.map($row.find('td'), function(element) {
return $(element).text()
}).join(' ');
if (id.indexOf(value) < 0) {
$row.hide();
} else {
$row.show();
}
嘗試這個。 你必須遍歷所有列,一旦找到任何匹配,只需使用return false;
轉義循環return false;
在each()
函數中。 此外,如果找不到string, indexOf返回-1。
$("#search").on("keyup", function() { var value = $(this).val(); $("table tr").each(function(index) { if (index !== 0) { $row = $(this); $row.find("td").each(function(){ var id = $(this).text(); if (id.indexOf(value) < 0) { $row.hide(); } else { $row.show(); return false; } }); } }); });
table, tr, td, th{ border: 1px solid blue; padding: 2px; } table th{ background-color: #999999; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr><th>Forename</th><th>Surname</th><th>Extension</th></tr> <tr><td>Jim</td><td>Carey</td><td>1945</td></tr> <tr><td>Michael</td><td>Johnson</td><td>1946</td></tr> </table> <br /> <input type="text" id="search" placeholder=" live search"></input>
$("#search").on("keyup", function() {
var value = $(this).val();
$("table tr").each(function(index) {
if (index !== 0) {
$row = $(this);
var id = $.map($row.find('td'), function(element) {
return $(element).text()
}).join(' ');
if (id.indexOf(value) <0) {
$row.hide();
}
else {
$row.show();
}
}
});
});
嘗試這個:
$("#search").on("keyup", function() {
var value = $(this).val();
$("table td").each(function() {
if(value.match($(this).text)) {
console.log($(this).text());
}
else {
$("table").hide();
}
});
});
嘗試與所有td元素匹配。
希望這有效,
$("#search").on("keyup", function() {
var value = $(this).val();
$("table tr").each(function(index) {
if (index !== 0) {
var id = $(this).children().text()
if (id.indexOf(value) < 0) {
$(this).hide();
}else {
$(this).show();
}
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.