javascript - 将事件更改为 on.click 以进行搜索
问题描述
我在下面找到了这个片段,它突出显示并跳转到搜索词。当前的代码片段在用户输入的每次击键后进行搜索,这对服务器造成了太大的压力。相反,我希望它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
按键上调用它,如果没有结果,也可以在下一次/上一次点击中调用。
但是仍然存在一些问题,例如如果值发生更改,您无法使用下一个/上一个按钮进行搜索,因此需要一些额外的工作。
推荐阅读
- youtube - youtube 中的 yt、ytd、ytd-app 类型的 html 标签是什么?
- html - 如何使用 CSS 将每个单词的第一个字母大写我还尝试了其他股权溢出问题但没有奏效?
- python - 根据行值更改连接条件
- c# - 如何将 Json 反序列化为简单的字典
- node.js - 为相同的ID分隔存储在数组中的数据?
- php - PHP - glob() 使用 $variable 时不返回结果
- c# - 使用 if 同时搜索表中的多个项目
- .net - Web API 2 每个控制器的通用路由
- quarkus - Quarkus 会话为 NULL
- php - php好友请求系统未从提交按钮发送正确数据