I have two unordered lists, a bit like:
<ul class="list1">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li class="current">Item 4</li>
<li>Item 5</li>
</ul>
<ul class="list2">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
And the goal is, with jquery, to identify which li is marked with the开发者_如何学编程 'current' class and then add a class to the second list to the corresponding li. I just can't think of how to do this.
Thanks.
$('ul.list2 li:nth-child(' + $('ul.list1 li.current').index() + ')').addClass('current');
Or you could make it a little less icky:
$('ul.list2 li').eq($('ul.list1 li.current').index()).addClass('current');
The second one, I like better, now that I get to see them both :-) The tricks here are:
- the "eq" filter lets you pick an element from a jQuery list based on an index;
- the "index" function lets you find the index of an element relative to its siblings in the DOM
Just simply use this:
var initialIndex = $('.list1 .current').index();
$('.list2 li').eq(initialIndex).addClass('current');
// Find the current item in the first list, remember its text
var textToMatch = $('ul.list1 li.current').text();
// Loop through each li in the second list
$('ul.list2 li').each(function(index, domElement){
var curr = $(domElement);
// if the text matchs the first then add our class
if(textToMatch == curr.text()){
curr.addClass('NEWCLASS');
}
});
EDIT1:This is answering the wrong question, the question has since been clarified I will leave this here as it still seems nice :)
EDIT2: as Per Flex, this is a nicer way to achive the same thing, again not what the question was after.
$('.list2 li:contains("' + // Find an li in list2 which contains
$('.list1 li.current').text() + '")') // the same text as the as the current li in list1
.addClass("NEWCLASS"); // and add our new class to it
$('li.current + li').addClass('yourClass')
edit: misunderstanding of the question
var index = $.inArray($('li.current')[0],$('li.current').parent().children());
$('ul:eq(1) li:eq('+index+')').addClass('selected');
精彩评论