gpt4 book ai didi

javascript - Jquery 通过分离/追加过滤行

转载 作者:行者123 更新时间:2023-11-28 03:40:47 25 4
gpt4 key购买 nike

我知道隐藏/显示,但我想知道如何使用 Jquery 的分离从 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();
}
});
});

最佳答案

“交替行为”的原因是由于以下逻辑:

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" />

关于javascript - Jquery 通过分离/追加过滤行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57318467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com