开发者

jQuery -- adding and removing a class using next() across paragraphs

开发者 https://www.devze.com 2023-04-04 14:09 出处:网络
I have a document and it\'s got a variety of spans in it with the class .highlight on them. The first selected item also has .currentItem on it, indicating it\'s the开发者_开发百科 one currently selec

I have a document and it's got a variety of spans in it with the class .highlight on them. The first selected item also has .currentItem on it, indicating it's the开发者_开发百科 one currently selected. I want to be able to browse to the next highlighted item when the user clicks a button. Here's the function that, best as I can tell, should work:

function goNextHighlight() {
    var $active = $('.currentItem');
    var $next = $('.currentItem').next('.highlight');

    $active.removeClass('currentItem');
    $next.addClass('currentItem');
}

$active is being set properly, and it's removing the currentItem class from it. However, $next often doesn't work because the next highlighted item is in another div or paragraph. Here's a jsfiddle that shows the problem. If you click on the next button twice, you'll see it works the first time, but not the second.

How do I make this work so that it'll go to the next matching .highlight, regardless of where in the document it is?


var $next = $('.highlight').eq($active.index('.highlight')+1);

Example: http://jsfiddle.net/Paulpro/qjsjt/1/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号