【发布时间】:2015-12-24 06:23:01
【问题描述】:
这些年来我使用了无数的 Stack Overflow 解决方案,但这是我第一次发帖。
我正在 Wordpress 网站上构建一个页面内搜索工具,其功能类似于浏览器的查找功能。当用户开始在搜索字段中输入时,匹配的字母会被一个绿色背景的 class="highlight" 包围。这很好用。
我还希望能够遍历匹配项。当单击 Next 或 Previous 按钮时,“current”被添加到 span 类 - class="highlight current" 具有黄色背景。每次单击“下一步”按钮,下一个匹配项都会以黄色突出显示。上一个按钮突出显示上一个匹配项。
我正在使用 jQuery 的 .index() 和 .eq() 方法来确定将“当前”类添加到哪个匹配的跨度。我遇到的问题是 $('.highlight').index('current') 只匹配第一次点击后的元素,而不是后续点击后的元素。
这是我的代码的相关部分:
$('.search-btn').click(function (e) {
e.preventDefault();
var total_matches = [];
$('.highlight').each(function() {
total_matches.push(this);
});
console.log(total_matches.length);//total number of matched terms on the page
var current_selected = $('.highlight').index('current');
//term currently highlighted in yellow, -1 if nothing is highlighted.
//It ALWAYS returns -1, which is the problem
if( $(this).hasClass( 'search-next') ) {//click Next button
if(current_selected === -1) {//nothing currently selected
$( $('.highlight').eq(0) ).addClass('current');//highlight first element
}else{//something already selected
current_selected = (current_selected+1) % all_matches.length;
$( $('.highlight').eq(current_selected) ).addClass('current');
}
}
//something similar for the search-prev button....
});
我遗漏了一些与动态添加和删除的“当前”类有关的东西,但我无法弄清楚。
【问题讨论】:
-
.index('.current')
标签: javascript jquery