html - Jquery 从隐藏开始并在搜索过滤器上显示一定数量的元素
问题描述
我试图从隐藏 p 元素开始,然后在搜索时我只想显示前 2 行。例如,如果我在搜索框中输入 2,它将隐藏示例 1 和示例 1,并显示示例 2 和示例 2。如果我在搜索框中输入 1,它将隐藏示例 2 和示例 2,并显示示例 1 和示例1. 如果我在搜索框中输入 X,它只会显示 2 个示例(我不在乎哪个示例)。
<input type="text" id="tableAgain">
<div id="tableAgain2">
<p>Example 1</p>
<p>Example 1</p>
<p>Example 2</p>
<p>Example 2</p>
</div>
</body>
</html>
$(document).ready(function() {
$("p").hide();
$("#tableAgain").on("keyup", function() {
var value = $("#tableAgain").val().toLowerCase();
var txt = $('#tableAgain');
if (txt.val() != null && txt.val() != '') {
$("p:nth-child(1)").show();
$("p:nth-child(2)").show();
$("p:nth-child(3)").hide();
$("p:nth-child(4)").hide();
$("p").filter(function() {
$("p").toggle($("p").text().toLowerCase().indexOf(value) > -1)
});
} else {
$("p").hide();
}
});
});