2016-09-11 42 views
5

所以我有两个无序列表,其中有相同数量的项目。所以让我们假设无序列表#2中的项目全部隐藏。使它们出现的唯一方法是如果您单击无序列表#1中的项目。带索引的jQuery目标元素()

所以基本上

<ul class="list1"> 
    <li>item 1</li> 
    <li>item 2</li> 
    <li>item 3</li> 
    <li>item 4</li> 
</ul> 
<ul class="list2"> 
    <li class="hide">item 1</li> 
    <li class="hide">item 2</li> 
    <li class="hide">item 3</li> 
    <li class="hide">item 4</li> 
</ul> 

现在我试图做到这一点的方法是使用index()的方法,但我不知道如何正确处理这个代码。

这就是我想到的。

$('.list1').on('click', 'li', function() { 
    $('.list2 li').index($(this).index()).toggleClass('active'); 
}); 

所以当你在.list1点击一个行项目,无论是行项目的指标,是我想在.list2

我遇到的问题为目标的指数,当我控制台记录它,我得到奇怪的索引号。第一个订单项显示为2而不是0,第二个订单项的索引为-1。

我做错了什么?我很确定。

在此先感谢你们!

+0

尝试使用.EQ选择与指数的组合。 https://api.jquery.com/eq/ –

+0

[jQuery.index](https://api.jquery.com/index/)总是返回索引,您正在寻找[jQuery.eq](https:/ /api.jquery.com/eq/),它将匹配元素的集合减少到指定索引处的匹配元素集合。 –

回答

5

jquery .index()返回所选元素的索引。您需要使用:eq()选择器或.eq()方法来选择具有索引的元素。

$('.list1').on('click', 'li', function() {  
 
    $('.list2 li').eq($(this).index()).toggleClass('active'); 
 
});
.hide { display: none; } 
 
.active { display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<ul class="list1"> 
 
    <li>item 1</li> 
 
    <li>item 2</li> 
 
    <li>item 3</li> 
 
    <li>item 4</li> 
 
</ul> 
 
<ul class="list2"> 
 
    <li class="hide">item 1</li> 
 
    <li class="hide">item 2</li> 
 
    <li class="hide">item 3</li> 
 
    <li class="hide">item 4</li> 
 
</ul>

+0

非常感谢您的输入。这真太了不起了。不幸的是我遇到了另一个问题 - 它将.not()和.eq()混合在一起。但这是另一个线程。非常感谢,这工作! – giantqtipz

3

试试这个,这会为你工作精细

<html> 
 
<head></head> 
 
<title></title> 
 

 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
 
<style type="text/css"> 
 

 
/* in here we get the ul which the class name is list2 and get the li elements inside it and hide those first*/ 
 
ul.list2 li{ 
 
    display: none; 
 
} 
 

 

 

 
</style> 
 

 
<body> 
 

 
<ul class="list1"> 
 
    <li>item 1</li> 
 
    <li>item 2</li> 
 
    <li>item 3</li> 
 
    <li>item 4</li> 
 
</ul> 
 

 
<ul class="list2"> 
 
    <li>item 1</li> 
 
    <li>item 2</li> 
 
    <li>item 3</li> 
 
    <li>item 4</li> 
 
</ul> 
 

 

 

 
</body> 
 

 
<script type="text/javascript"> 
 

 
$(document).ready(function(){ 
 
    $("ul.list1 li").click(function(){ 
 
    var theindex = $(this).index();//in here you get the index number of clicked li element inside list1 class 
 
    $("ul.list2 li").eq(theindex).slideToggle(500);//then in here, you show the same index li element in list2 , which we are hidden. 
 
    }); 
 
}); 
 

 
    
 

 
</script> 
 

 
</html>