Getting index of li which has a class and incrementing
I've been all around with hasClass, is(), if then etc.
What I'd like to do is when "btn" is clicked, look through 开发者_JS百科a list of li's, find the one that has the class of "on" and get its index value. Depending on that value, run function x, add the class "on" to the next li and remove the class from the current li.
I want to avoid running comparisons for every index value with a chain of if conditionals
I think I've just been mixing too many selectors and methods. Any code I post here would be even harder to read than possibly that question!
Thanks for those who may get what I'm trying to ask!
If you're using jQuery 1.4+ you can use .index()
without parameters to get the index of an element amongst its siblings, like this:
var i = $("li.on").index();
You can use the normal traversal methods for the rest, for example moving the class down one:
$("li.on").removeClass("on").next().addClass("on");
You can also try:
var current = $('ul.ulClass').find('li.on'); // select current on li
current.removeClass('on'); // Remove on from current
current.next().addClass('on'); // Add on to next
Demo
精彩评论