Javascript 使用jQuery通过类选择下一个元素,每次一个
背景故事:我在HTML中搜索了一个短语,它在每个实例周围放置了一个跨度。因此,如果我搜索Lorem,每个单词出现的地方都会是这样:Javascript 使用jQuery通过类选择下一个元素,每次一个,javascript,jquery,next,Javascript,Jquery,Next,背景故事:我在HTML中搜索了一个短语,它在每个实例周围放置了一个跨度。因此,如果我搜索Lorem,每个单词出现的地方都会是这样: <span class="live-search-highlight">Lorem</span> <span class="highlight-current">Lorem</span> jsFIDLE:如果您不删除“live search highlight”类,而是增加存储的索引,这会有所帮助。这允许您在文档中
<span class="live-search-highlight">Lorem</span>
<span class="highlight-current">Lorem</span>
jsFIDLE:如果您不删除“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;
});
检查小提琴:这应该可以
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++
});
创建所有高亮显示元素的集合更简单。 然后使用索引确定当前/下一个的位置 当到达最后一个时,以下操作将恢复到开始
// 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会通过其父级的兄弟姐妹突出显示。这是第一次工作,因为第一个高光的父级与第二个高光处于同一级别。之后它就不起作用了,因为它会在身体的兄弟姐妹中寻找高光
body
h1
highlight1 -> parent = h1 (has highlight siblings)
highlight2 -> parent = body (doesn't have any siblings)
highlight3
您必须存储以下内容之一:
高亮显示并遍历数组,而不是遍历树,或者
当前高亮显示的索引
如果您创建一个包含所有LOREM的数组,那么您可以使用jquery eq(索引)按顺序引用它们。我简直不敢相信没有办法说“嘿,jQuery…为我找到这个类的下一个实例。”看起来如此简单。$('.live search highlight')将返回一个您需要开始的元素数组。然后,您只需手动跟踪索引。您还可以使用jQuery的.index()方法在其余的“live search highlight”项目中轻松检索“highlight current”项目的索引$(“.live search highlight”).index($(“.highlight current”);然后你可以简单地增加它,或者当你达到长度-1时将其设置回零。来自@charlietfl的解决方案就是我在上一篇评论中解释的。做得很好。我正在研究类似的答案,你比我抢先一步D
body
h1
highlight1 -> parent = h1 (has highlight siblings)
highlight2 -> parent = body (doesn't have any siblings)
highlight3