我有一个页面,最终将有10个不同的UL,每个LI中有多个DIV,每个LI都应该可以搜索到LI中的每个DIV。每个搜索框应该单独搜索自己的UL,而不会影响页面中的其他UL。我目前使用的解决方案是复制搜索代码,同时以数字方式递增选择器。这会产生很多冗余。Multipe JQuery在单个页面中搜索
如何限制冗余度并让每个搜索仍然只影响其自己的UL?
以下是递增的代码(仅而不是两次所有10为简洁起见):
的HTML:
<h1>Search One</h1>
<input type="text" id="search1" value="" placeholder="enter search text" />
<div id="results1">
<ul>
<li>
<div class="listing-three">Apple</div>|
<div class="listing-three">Banana</div>|
<div class="listing-three">Cherry</div>
</li>
<li>
<div class="listing-three">Apple</div>|
<div class="listing-three">Banana</div>|
<div class="listing-three">Cucumber</div>
</li>
<li>
<div class="listing-three">Apple</div>|
<div class="listing-three">Berry</div>|
<div class="listing-three">Cheese</div>
</li>
</ul>
</div>
<h1>Search Two</h1>
<input type="text" id="search2" value="" placeholder="enter search text" />
<div id="results2">
<ul>
<li>
<div class="listing-three">Apple</div>|
<div class="listing-three">Banana</div>|
<div class="listing-three">Cherry</div>
</li>
<li>
<div class="listing-three">Apple</div>|
<div class="listing-three">Banana</div>|
<div class="listing-three">Cucumber</div>
</li>
<li>
<div class="listing-three">Apple</div>|
<div class="listing-three">Berry</div>|
<div class="listing-three">Cheese</div>
</li>
</ul>
</div>
jQuery的
$("#search1").keyup(function() {
var searchText = $(this).val().toLowerCase();
$("#results1 li").each(function() {
console.log($(this).text());
var string = $(this).text().toLowerCase();
if (string.indexOf(searchText) != -1) {
$(this).show("slow");
} else {
$(this).hide("slow");
}
});
});
$("#search2").keyup(function() {
var searchText = $(this).val().toLowerCase();
$("#results2 li").each(function() {
console.log($(this).text());
var string = $(this).text().toLowerCase();
if (string.indexOf(searchText) != -1) {
$(this).show("slow");
} else {
$(this).hide("slow");
}
});
});
为了便于解释和清晰的功能,我添加了小提琴。
https://jsfiddle.net/MercyMayaGames/1pbwc98j/
使用类选择。插件mySearch()你可以使用$(id1).mySearch(),$(id2).mySearch()等... https://learn.jquery.com/plugins/basic-plugin-creation/ – daremachine