所以我做這段代碼時,當用戶在文本框中搜索查詢時,它會突出顯示內容中某處的查詢並重點關注該查詢的第一次出現。問題在於,當用戶輸入類似li或div這些是HTML標記時,這些也會顯示爲搜索結果。例如,這裏是我的HTML標記Javascript:搜索和突出顯示包含HTML標記
<div class="col-lg-6" id="search-area">
<div class="input-group">
<input type="text" id="search-term" class="form-control">
<span class="input-group-btn">
<button id="search-button" class="btn btn-default"><span class="glyphicon glyphicon-search"></span></button>
</span>
</div><!-- /input-group -->
</div>
<h3>Did we miss something? Have any more FAQs to add? Contact us directly at [email protected]</h3>
這裏是我的js
function searchAndHighlight(searchTerm, selector) {
if(searchTerm) {
var selector = selector || "#mainContainer";
var searchTermRegEx = new RegExp(searchTerm,"ig");
var matches = $(selector).text().match(searchTermRegEx);
if(matches) {
$('.highlighted').removeClass('highlighted'); //Remove old search highlights
$(selector).html($(selector).html()
.replace(searchTermRegEx, "<span class='highlighted'>"+searchTerm+"</span>"));
if($('.highlighted:first').length) { //if match found, scroll to where the first one appears
$(window).scrollTop($('.highlighted:first').position().top);
}
return true;
}
}
return false;
}
$(document).ready(function() {
$('#search-button').on("click",function() {
if(!searchAndHighlight($('#search-term').val())) {
alert('No results found for query "'+$('#search-term').val()+'".');
}else{
alert($("span[class='highlighted']").length);
}
});
$("#search-term").keypress(function(event) {
if (event.which == 13) {
if(!searchAndHighlight($('#search-term').val())) {
alert('No results found for query "'+$('#search-term').val()+'".');
}else{
alert($("span[class='highlighted']").length);
}
}
});
});
如果用戶輸入H3例如,其結果將是
<**h3**>Did we miss something? Have any more FAQs to add? Contact us directly at [email protected]</**h3**>
不該」它說沒有找到結果?
我忘記,這裏是我的js文件 – Growlithe
你能提供一個jsfiddle嗎? – Shahe