我知道隐藏/显示,但是我想知道如何使用Jquery的detach从DOM中删除行并将它们附加回去。我想通过输入实时过滤html表。
此代码似乎可以在其他所有击键中使用
$(document).ready(function () {
var tablerows;
$('#filter').on("input", function () {
let term = $(this).val().trim();
if (tablerows) {
$(tablerows).appendTo('#main')
tablerows = null;
} else {
tablerows = $("#main tr:not(:first-child, :icontains('" + term + "'))").detach();
}
});
});
答案 0 :(得分:0)
“替代行为”的原因是由于以下逻辑:
if (tablerows) {
/*
The problem is here, in that you are always adding the current
tablerows back into the table
*/
}
else {
/*
..
*/
}
为使此方法按要求工作,您需要在if (tablerows)
情况下扩展逻辑,以确保当前的过滤条件不包含在当前tablerows
中。如果当前术语未出现在当前分离的tablerows
中,那么此时您需要将这些术语重新引入表格中:
$(document).ready(function() {
var tablerows;
$('#filter').on("input", function() {
let term = $(this).val().trim();
if (tablerows) {
/*
Also note that an empty term string needs to be accounted for
which the :contains selector won't account for, hence the !term
*/
if ($(":contains('" + term + "')", tablerows) === false || !term)
{
/*
No match for filter terms so add tablerows back to table
*/
$(tablerows).appendTo('#main')
tablerows = null;
}
} else {
/*
There was a typo here, it should read :contains (not :icontains)
*/
tablerows = $("#main tr:not(:first-child, :contains('" +
term + "'))").detach();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js">
</script>
<table id="main">
<tr>
<td>test</td>
</tr>
<tr>
<td>foo</td>
</tr>
<tr>
<td>bar</td>
</tr>
</table>
<input id="filter" />