我正在尝试使用实时搜索构建常见问题解答页面 - 搜索结果会被隐藏并显示为用户类型。下面的脚本运行良好,除了我想突出显示用户类型的搜索文本。
HTML
<form id="live-search" action="" class="styled" method="post">
<fieldset>
Search: <input type="text" class="text-input" id="filter" name="filter" value="" />
</fieldset>
</form>
<div id="content-block">
<div class="faq">
<div class="arrow right"></div>
<div class="question">
Can I send Greek characters?
</div>
<div class="answer">
The systems support so-called Unicode messages, but because this concerns an extended
character set the message is limited to 70 characters.
</div>
</div>
的jQuery
$(document).ready(function(){
$("#filter").keyup(function(){
// Retrieve the input field text and reset the count to zero
var filter = $(this).val(), count = 0;
if(!filter){
//$(".commentlist li").hide();
$(".answer").hide();
return;
}
var regex = new RegExp(filter, "i");
// Loop through the comment list
//$(".commentlist li").each(function(){
$(".answer").each(function(){
// If the list item does not contain the text phrase fade it out
if ($(this).text().search(regex) < 0) {
//$(this).hide();
$(this).fadeOut('slow')
// Show the list item if the phrase matches and increase the count by 1
} else {
//$(this).show();
$(this).fadeIn('slow');
count++;
}
});
// Update the count
var numberItems = count;
$("#filter-count").text("Number of Comments = "+count);
});
});
演示中的脚本演示:http://jsfiddle.net/mrynart/buw23asn/5/
任何帮助非常感谢。
答案 0 :(得分:0)
我通过以下代码找到了解决问题的方法。 实时搜索现在以用户键入的方式显示搜索结果,并在用户输入时突出显示搜索到的文本。
<强> Jquery的强>
$(document).ready(function(){
var $filter = $("#filter"),
$answer = $(".answer");
$filter.keyup(function(){
// Retrieve the input field text and reset the count to zero
var filter = $(this).val(), count = 0;
if(!filter){
$answer.hide();
return;
}
var regex = new RegExp(filter, "i");
// Loop through the comment list
$answer.each(function(){
var pageText = $(this).text().replace("<span>","").replace("</span>"),
searchedText = $filter.val(),
theRegEx = new RegExp("("+searchedText+")", "igm"),
newHtml = pageText.replace(theRegEx ,"<span>$1</span>");
// If the list item does not contain the text phrase fade it out
if ($(this).text().search(regex) < 0) {
$(this)
.fadeOut('slow')
.attr("data-open", false);
// Show the list item if the phrase matches and increase the count by 1
} else {
$(this)
.fadeIn('slow')
.attr("data-open", true);
$(this).html(newHtml);
count++;
}
});
// Update the count
var numberItems = count;
$("#filter-count").text("Number of Comments = "+count);
});
});