只想使用 jquery 添加对加载表的搜索可能性,但下面的代码仅适用于第一列。我想让它适用于所有细胞。您能检查一下代码并帮我找出错误吗:
这是我的 html 代码:
<span id="search"></span>
这是我的js代码:
$("#search").on("keyup", function () {
var value = $(this).text();
$("table tr").each(function (index) {
if (index != 0) {
$row = $(this);
$row.each(function () {
var cell = $row.find("td").text();
if (cell.indexOf(value) != 0) {
$(this).hide();
} else {
$(this).show();
}
});
}
});
});
最佳答案
我认为您不需要执行 $row.each 因为您已经在每个中,请尝试在列上执行每个:
$("#search").on("keyup", function () {
var value = $(this).text();
$("table tr").each(function (index) {
if (index != 0) {
$row = $(this);
$row.find("td").each(function () {
var cell = $(this).text();
if (cell.indexOf(value) != 0) {
$(this).hide();
} else {
$(this).show();
}
});
}
});
});
编辑:
http://jsfiddle.net/rn8dsnwm/2/
$("#search").keyup(function () {
var value = $(this).val();
if (value.length){
$("table tr").each(function (index) {
if (index != 0) {
$row = $(this);
$row.find("td").each(function () {
var cell = $(this).text();
if (cell.indexOf(value) < 0) {
$row.hide();
} else {
$row.show();
return false; //Once it's shown you don't want to hide it on the next cell
}
});
}
});
}
else{
//if empty search text, show all rows
$("table tr").show();
}
});
关于jquery 搜索适用于一列而不是整个 html 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26191358/