Я хочу отложить триггер поиска до тех пор, пока пользователь не закончит ввод. Я использую функцию, созданную с помощью mark.js (https://markjs.io). Он выполняет поиск по типу пользователя и переходит к первому результату при его поиске. Проблема в том, что он ищет каждую комбинацию букв по мере ввода. I.E: поиск «help» Ищет «h», «he», «hel», «help». Учитывая размер документа, это смехотворно медленно. Есть ли что-то, что я могу сделать с этой функцией, чтобы заставить ее ждать, пока пользователь не сделает ввод?JQuery - поиск задержки до завершения ввода
Вот функция поиска Я использую:
$(function() {
// the input field
var $input = $("input[type='search']"),
// clear button
$clearBtn = $("button[data-search='clear']"),
// prev button
$prevBtn = $("button[data-search='prev']"),
// next button
$nextBtn = $("button[data-search='next']"),
// the context where to search
$content = $(".container"),
// jQuery object to save <mark> elements
$results,
// the class that will be appended to the current
// focused element
currentClass = "current",
// top offset for the jump (the search bar)
offsetTop = 150,
// the current index of the focused element
currentIndex = 0;
/**
* Jumps to the element matching the currentIndex
*/
function jumpTo() {
if ($results.length) {
var position,
$current = $results.eq(currentIndex);
$results.removeClass(currentClass);
if ($current.length) {
$current.addClass(currentClass);
position = $current.offset().top - offsetTop;
window.scrollTo(0, position);
}
}
}
/**
* Searches for the entered keyword in the
* specified context on input
*/
$input.on("input", function() {
var searchVal = this.value;
$content.unmark({
done: function() {
$content.mark(searchVal, {
accuracy: "exactly",
separateWordSearch: false,
done: function() {
//Filter Results//$context.not(":has(mark)").hide();
$results = $content.find("mark");
currentIndex = 0;
jumpTo();
}
});
}
});
});
/**
* Clears the search
*/
$clearBtn.on("click", function() {
$content.unmark();
$input.val("").focus();
});
/**
* Next and previous search jump to
*/
$nextBtn.add($prevBtn).on("click", function() {
if ($results.length) {
currentIndex += $(this).is($prevBtn) ? -1 : 1;
if (currentIndex < 0) {
currentIndex = $results.length - 1;
}
if (currentIndex > $results.length - 1) {
currentIndex = 0;
}
jumpTo();
}
});
});
Вот некоторые HTML:
<input type="search" placeholder="Search" class="text-input" style="height: 28px; border-style: solid; border-color: black; border-width: 1px; margin-bottom: 3px;">
<br/>
<button data-search="next">Next</button>
<button data-search="prev">Previous</button>
<button data-search="clear">✖</button><br/>
<div class="container">
<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus elementum non arcu id tristique. Cras fringilla nisi erat, non ultricies leo varius eu. Duis venenatis enim sed tristique gravida. Nulla dolor augue, tempor non nisl eget, consequat consequat magna. Nulla quis elit nisl. Integer at tortor molestie, dignissim odio id, pharetra nunc. Maecenas scelerisque porta erat bibendum aliquet. Proin est felis, pretium sit amet consequat eu, aliquet ac erat. Donec tempus, libero sit amet rutrum posuere, leo ipsum gravida odio, quis sodales magna nisl ut lectus.
</div>
</div>
Вы можете установить setInterval или начать поиск после того как длина строки длиннее 3 символов (например). –
Какую версию mark.js вы используете? Есть недавний релиз, который обеспечивает оптимизацию производительности. – dude