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

时间:2015-12-23 22:10:53

标签: javascript jquery

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

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

我还希望能够迭代匹配。单击“下一个”或“上一个”按钮时,"当前"被添加到span类 - class ="突出显示当前"它有黄色背景。每次单击“下一步”按钮,下一个匹配将以黄色突出显示。上一个按钮突出显示上一个匹配。

我正在使用jQuery的.index()和.eq()方法来确定添加&#34;当前&#34;的匹配范围。上课。我遇到的问题是$(&#39; .highlight&#39;)。index(&#39; current&#39;)仅匹配第一次点击后的元素,而不是后续点击后的元素。< / p>

以下是我的代码的相关部分:

$('.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....
});

我错过了与&#34;当前&#34;有关的事情。正在动态添加和删除类,但我无法弄明白。

2 个答案:

答案 0 :(得分:2)

如果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....
});

答案 1 :(得分:1)

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