javascript - 使用 jQuery 通过类一次选择下一个元素

标签 javascript jquery jquery-selectors

背景故事: 我在 HTML 中搜索了一个短语,该短语在每个实例周围放置了一个跨度。因此,如果我搜索 Lorem,该词出现的每个地方都会如下所示:

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

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

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

问题:我想单击一个按钮,并从 .highlight-current 开始,我想找到 .live-search- 的下一个实例高亮并将其类切换为.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/

最佳答案

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

到达最后一个时,以下内容将恢复到开头

// 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');

我会离开主类,只添加/删除次要类

DEMO

关于javascript - 使用 jQuery 通过类一次选择下一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31394475/

相关文章:

javascript - Google图表不会总是在页面加载时加载

php - 更新标记时 Google map 停止重新居中

jquery - 使用多个 jQuery 选择器进行过滤

jquery - 如何选择区间之间的元素

javascript - 没有表格的文本字段

javascript - 在 Javascript 中使用两个变量从数组中进行选择

javascript - 如何在单击列表元素后保持突出显示?

javascript - 使用居中导航栏居中导航栏品牌形象

jquery正则表达式否定字母

javascript - 将 jQuery 选择器转换为新 DOM 元素的 HTML