如何用jQuery获取动态分类元素的索引

多年来我一直使用无数的Stack Overflow解决方案,但这是我第一次发布。

我正在Wordpress网站上构建一个页面内搜索工具,其function与浏览器的查找function类似。 当用户开始在搜索字段中键入时,匹配的字母被具有绿色背景的class =“highlight”的span包围。 这很好用。

我也想要能够迭代匹配。 单击“下一个”或“上一个”按钮时,“当前”将添加到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.... }); 

我错过了与动态添加和删除的“当前”类有关的内容,但我无法弄明白。

如果current是一个类,那么你需要预先设置一个句点。

没有句点,它正在寻找选择器的索引而不是

所以尝试替换它: var current_selected = $('.highlight').index('current');

使用: var current_selected = $('.highlight').index('.current');


我还注意到你在某些函数上双重包装jQuery $( $('element') )不是必需的。


最后,如果你没有使用total_matches你可以获得$('.highlight')的长度而不需要循环遍历它。

 $('.search-btn').click(function (e) { e.preventDefault(); var total_matches = $('.highlight').length; // shorter than looping through console.log(total_matches);//total number of matched terms on the page var current_selected = $('.highlight').index('.current'); // fix is here if(! $(this).hasClass( 'search-next') ) return; // I find this easier than indenting everything below if (current_selected === -1) {//nothing currently selected $('.highlight').eq(0).addClass('current');//highlight first element } else {//something already selected current_selected = (current_selected+1) % total_matchces; $('.highlight').eq(current_selected).addClass('current'); } //something similar for the search-prev button.... }); 

您永远不会从先前选定的元素中删除current类,因此始终只选择第一个。