背景故事: 我在 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');
});
最佳答案
更简单的是,只需创建所有突出显示元素的集合。 然后使用索引来确定当前/下一个的位置。
到达最后一个时,以下内容将恢复到开头
// 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');
我会离开主类,只添加/删除次要类
关于javascript - 使用 jQuery 通过类一次选择下一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31394475/