我正在构建一个产品搜索演示,该产品搜索示例会根据搜索词过滤商品。
键入时,文本框将动态地将搜索查询与标签标记中的关键字进行匹配。如果所有关键字都匹配,则父div保持可见。如果缺少关键字,则div消失。
我正在尝试添加一个停用词列表,以便可以过滤常见的短语结构。理想情况下,它们将由stopword.js或.txt调用。 (这是一个演示,需要脱机工作)
这样做的原因是,我希望在查询为空时所有框都可见,并且仅在新关键字不匹配时逐渐消失。
预先感谢您的帮助。
提琴:https://jsfiddle.net/eqn5h7vk/
代码:
$("#search-input").keyup(function(){
// Retrieve the input field text and reset the count to zero
var filter = $(this).val(), count = 0;
// Loop through the word list
$(".content_boxes div").each(function(){
var pattern = filter.trim().match(/[a-zA-Z]+|[0-9]+/g) || ""; // null coalescing: "" if null
if(pattern) {
pattern = pattern.map(function(el) {
return '(?=.*' + el + ')';
});
//join if there is something in the array
pattern = pattern.join("");
}
//console.log(pattern.join(""));
// If the word list does not contain the text phrase, fade it out
if ($(this).text().search(new RegExp(pattern, "i")) < 0) {
$(this).fadeOut("slow");
// Show the product divs if the phrase matches and increase the count by 1
} else {
$(this).show();
count++;
}
});
// Update the count
var numberItems = count;
$("#filter-count").text("Number of Comments = "+count);
});
body {font-family:arial}
input {font-size:20px; border:1px solid #cecece; padding:5px; border-radius:5px; width:300px;}
b {color:blue}
label {display:none}
.content {width:100px; margin:5px; background:#cecece; float: left; border-radius:5px; padding:10px; text-align:center}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="search-input" type="text" Placeholder="Search fruit by color">
<p>Boxes will show up if keywords <b>Red</b>, <b>Green</b> or <b>Yellow</b> match the label</p>
<p>Im trying to add a list of stopwords so if you search for <b>"Show me yellow and green fruits"</b>, the keywords <b>show</b>, <b>me</b>, <b>and</b>, <b>fruits</b> are ignored by the search.
<div class="content_boxes">
<div class="content"><label>Red green</label><span>Apple</span></div>
<div class="content"><label>yellow</label><span>Banana</span></div>
<div class="content"><label>Red</label><span>Cherry</span></div>
<div class="content"><label>green red</label><span>Grapes</span></div>
<div class="content"><label>green</label><span>Kiwi</span></div>
<div class="content"><label>yellow</label><span>Lemon</span></div>
<div class="content"><label>green</label><span>Lime</span></div>
<div class="content"><label>green yellow</label><span>Pears</span></div>
<div class="content"><label>Red</label><span>Strawberry</span></div>
<div class="content"><label>red green</label><span>Watermelon</span></div>