通过jQuery逐个选择下一个元素

Select next element via class with jQuery one at a time

本文关键字:下一个 元素 选择 jQuery 通过      更新时间:2023-09-26

Backstory:我有一个搜索过短语的HTML,它在每个实例周围放置了一个跨度。如果我搜索Lorem,每个出现这个词的地方都是这样的

<span class="live-search-highlight">Lorem</span>

给它一点亮点。第一个实例被赋予一个不同的类,具有更明显的亮点,如下所示:

<span class="highlight-current">Lorem</span>

问题:我想点击一个按钮,从.highlight-current开始,我想找到.live-search-highlight的下一个实例,并将其类切换到.highlight-current。如何用jQuery实现这一点?以下是目前为止我所做的,它只工作一次:

$(document.body).on('click','.button', function(){
    // Find highlight-current, then get the next instance and make that one current
    $('.highlight-current').parent().nextAll(".live-search-highlight").eq(0).removeClass('live-search-highlight').addClass('highlight-current');
    // Reset the previous one so it's no longer current
    $('.highlight-current:first').removeClass('highlight-current').addClass('live-search-highlight');
});

JsFiddle: http://jsfiddle.net/kthornbloom/g5skaek7/3/

创建所有突出显示元素的集合更简单。然后使用索引来确定当前/下一个位置。

当到达最后一个时,Following将恢复到开始

// create collection of all highlighted elements
var $highlights = $('.live-search-highlight'),
    // isolate the current one from collection and remove the secondary class
    $currHighlight = $highlights.filter('.highlight-current').removeClass('highlight-current'),
    // use index of current to determine next
    nextIndex = $highlights.index($currHighlight) + 1;
// revert to beginning if index is at the end
if(nextIndex === $highlights.length){
    nextIndex = 0;
}
// add secondary class to next (or first) in collection
$highlights.eq(nextIndex).addClass('highlight-current');

我将保留主类,只添加/删除次要类

演示

如果您不删除'live-search-highlight'类,而是增加您存储的索引,则会有所帮助。这允许您在文档中循环,并将使实现前进/后退控制变得容易。

var currentIndex = 0,
totalMatches = 0,
currentClass = 'highlight-current',
normalClass = 'live-search-highlight';
$(document.body).on('click','.button', function(){
    var matches = $('.'+normalClass);
    totalMatches = matches.length;
    if(totalMatches === 0){
        return;
    }
    var newIndex = (currentIndex === totalMatches - 1) ? 0 : currentIndex + 1;
    matches.eq(currentIndex).removeClass(currentClass);
    matches.eq(newIndex).addClass(currentClass);
    currentIndex = newIndex;
});

检查小提琴:http://jsfiddle.net/e00x5pbd/1/

问题是,您的代码查找下一个.live-search-highlight通过它的父的兄弟姐妹。这在第一次工作是因为第一个高亮的父级与第二个高亮处于同一级别。之后它就不能工作了,因为它会在body的兄弟中寻找高光。

body
    h1
        highlight1 -> parent = h1   (has highlight siblings)
    highlight2     -> parent = body (doesn't have any siblings)
    highlight3

你必须存储:

  1. 突出显示并遍历数组而不是树遍历,或者
  2. 当前高亮显示的索引

应该可以。

var item_count = 0
$('.button').click(function(){
    $('.live-search-highlight').eq(item_count - 1).removeClass('highlight-current');
    $('.live-search-highlight').eq(item_count).addClass('highlight-current');
    item_count++
});

JSFiddle