【发布时间】:2017-12-14 21:15:19
【问题描述】:
我想创建一个有两个搜索框的应用程序。 我将搜索关键字传递给第一个框,然后传递给第二个框。 不幸的是,该应用程序不保留第一次搜索。输入第二个框时,第一个搜索被覆盖。
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
pre, p{
background-color:#987563;
}
.myInput{
background-color: #1c1d22;
color: white;
article{
background-color: #acac9a;
padding: 2%;
margin: 2%;
}
</style>
<script>
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myDIV *").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
$("#myInput1").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myDIV *").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
</head>
<body>
<input id="myInput" type="text" placeholder="Search..">
<input id="myInput1" type="text" placeholder="Search..">
<section id="myDIV">
<h2> If I type "two" in the first searchbox and than "three" in second, the second searchbox overwrites the first.</h2>
<p>one two </p>
<p>one three </p>
</section>
</body>
</html>
请问是否可以保留第一次搜索的结果并在第一个搜索上进行第二次搜索?
【问题讨论】:
-
如果你想保留两个搜索框的结果,我会简单地为两个框实现相同的搜索功能——搜索一个或搜索另一个。通过两次做同样的事情,你会毁掉一个或另一个。只是一个想法——给他们两个同一个类,然后实现函数来过滤#div1 以获取该类的输入内容。
-
我建议改用类。对于第一个过滤器,与您的第一个过滤器不匹配的所有内容,添加“hideFilterOne”或没有显示的内容。并为第二个使用“hideFilterTwo”或其他东西做同样的事情。然后如果过滤器二不会添加隐藏类,它仍然可以被第一个过滤器隐藏。他们可以独立运作,但也可以一起工作。
-
虽然附注。您确实应该使用 each() 而不是 filter() 因为您没有正确使用该方法。
$("#myDIV *").hide().filter(function(){ return this.innerHTML.toLowerCase().indexOf(value) > -1; }).show()
标签: javascript jquery search filter