[英]Changing event to on.click for searching terms
我在下面找到了這個片段,它突出顯示並跳轉到搜索詞。 當前的代碼片段在用戶輸入的每次擊鍵后進行搜索,這對服務器造成了太大的壓力。 相反,我希望它在用戶按下回車鍵或單擊下一步按鈕后mark
和跳轉。 我嘗試更改以下行,但它破壞了代碼。 有任何想法嗎?
$input.on("input", function() {
至
$nextBtn.on('click', function() {
代碼在這里:
$(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 = $(".content"),
// 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 = 50,
// 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, {
separateWordSearch: true,
done: function() {
$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();
}
});
});
工作 JSFiddle 在這里找到: https://jsfiddle.net/83nbm2rv/
您可以將$input.on('input')
更改為:
$input.on("keypress", function(e) {
if (e.which === 13) {
var searchVal = this.value;
$content.unmark({
done: function() {
$content.mark(searchVal, {
separateWordSearch: true,
done: function() {
$results = $content.find("mark");
currentIndex = 0;
jumpTo();
}
});
}
});
}
});
這將處理在文本框中按enter
鍵。 請參閱此小提琴以獲取下一個按鈕單擊更新: https://jsfiddle.net/9g4xr765/
基本方法是功能化內容標記並在$input
按鍵上調用它,如果沒有結果,也可以在下一次/上一次點擊中調用它。
但是仍然存在一些問題,例如如果值發生更改,您無法使用下一個/上一個按鈕進行搜索,因此需要一些額外的工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.