поэтому я делаю этот код, когда пользователь ищет запрос в текстовом поле, он будет выделять запрос где-то в содержании и фокусируется на первом возникновении этого запроса. Проблема заключается в том, что когда пользователь вводит что-то вроде li или div, которые являются тегами HTML, они также отображаются как результаты поиска. Например, вот моя разметка 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**>
не следует ли говорить, что результатов не найдено?
Ниже приведена функция ванильного JavaScript, которую я использую для выделения текста внутри текстовых узлов:
function highlightText(text, node) {
var searchText = $.trim(text).toLowerCase(),
currentNode = node,
matchIndex, newTextNode, newSpanNode;
while ((matchIndex = currentNode.data.toLowerCase().indexOf(searchText)) >= 0) {
newTextNode = currentNode.splitText(matchIndex);
currentNode = newTextNode.splitText(searchText.length);
newSpanNode = document.createElement("span");
newSpanNode.className = "highlight";
currentNode.parentNode.insertBefore(newSpanNode, currentNode);
newSpanNode.appendChild(newTextNode);
}
}
Чтобы найти текстовые узлы внутри HTML, вы можете использовать jQuery.contents()
. Вот пример:
var text = "faq";
$("body *").contents().filter(function () {
return this.nodeType === this.TEXT_NODE;
}).each(function () {
highlightText(text, this);
});
Попытайтесь изменить свой код, чтобы взаимодействовать со всеми дочерними узлами и проверить их val() вместо html():
....
var selector = selector || "#mainContainer";
var searchTermRegEx = new RegExp(searchTerm,"ig");
var matches = [];
$.each($(selector).children(), function(index, item){
matches.push($(item).val().match(searchTermRegEx));
});
if(matches) {....