我有一個頁面,最終將有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