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



这些年来,我使用了无数的Stack Overflow解决方案,但这是我第一次发帖。

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

我还希望能够迭代匹配。单击"下一步"或"上一步"按钮时,"当前"将添加到具有黄色背景的span class="高亮显示当前"中。每次单击"下一步"按钮,下一个匹配项都会以黄色突出显示。上一个按钮高亮显示上一个匹配。

我正在使用jQuery的.index()和.eq()方法来确定要将"current"类添加到哪个匹配的span。我遇到的问题是$('.highlight').index只在第一次单击后匹配元素,而不是在随后的单击后匹配。

这是我代码的相关部分:

$('.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是一个类,那么您需要准备一个句点。

如果没有周期,它将查找<current></current>选择器的索引,而不是<anything class="current"></anything>

因此,请尝试替换此: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类,因此始终只选择第一个。

最新更新