2013-07-23 19 views
0

我试图在用户点击特定图标时在列表中显示一个列表。 这是我的代码。如何在使用JQuery的类之后获取唯一的下一个元素?

HTML:

<li class="filename"><img src="expand.png" /> Lorem ipsum dolor sit amet</li> 
<ul class="datalog"> 
    <li>Lorem ipsum dolor sit amet</li> 
    <li>Lorem ipsum dolor sit amet</li> 
    <li>Lorem ipsum dolor sit amet</li> 
</ul> 
<li class="filename"> 
<img src="expand.png" /> Lorem ipsum dolor sit amet</li> 
<ul class="datalog"> 
    <li>Lorem ipsum dolor sit amet</li> 
    <li>Lorem ipsum dolor sit amet</li> 
    <li>Lorem ipsum dolor sit amet</li> 
</ul> 

JQuery的:

$('.filename img').click(function() { 
    $('.filename').next(".datalog").show(); 
}); 

而这里的JSFiddle

我也试着像最近或儿童的功能,可能不好实现的,但没有成功。

在我的例子中只有两个主要列表,但在应用程序中列表的数量是可变的(所以我不能真正使用索引)。

如何只显示与点击相关的列表?

回答

3

使用this参考

$('.filename img').click(function() { 
    $(this).parent().next(".datalog").show(); 
}); 

解释

$(this)-->current clicked element , which is img 
parent()--> go to parent which is `li` 
.next(".datalog") --> go to the next element whose class is `.datalog`, that is `ul` 
.show() -->show 

fiddle here

+0

'$(这)'似乎不工作。如果我尝试再次使用'$('。filename')',我得到了相同的结果(顺便说一句,我意识到这是合乎逻辑的,因为它定义了所有的类...)。 – Alex

+0

yup ...检出小提琴... – bipen

+0

好吧,我明白了,谢谢;) – Alex

2

你可以这样做:

$('.filename img').click(function() { 
    $(this)     // Get the current img being clicked 
     .closest('li')  // Go to the closest parent `li` to the img 
     .next('.datalog') // Go to the next sibling of the `li` 
     .show();    // Show the `ul` with the class `.datalog` 
}); 

FIDDLE DEMO #1

你也可以试试这个:

$('.filename img').click(function() { 
    $(this).closest('li').next('.datalog').show().siblings('.datalog').hide(); 
}); 

FIDDLE DEMO #2

0

尝试一下本作全过程

$(document).ready(function(){ 

    $('.filename img').click(function() { 
     if($(this).closest('li').next('.datalog').is(':hidden')) { 
     $(this)     // Get the current img being clicked 
      .closest('li')  // Go to the closest parent `li` to the img 
      .next('.datalog') // Go to the next sibling of the `li` 
      .show();    // Show the `ul` with the class `.datalog` 
     } else { 
       $(this)     // Get the current img being clicked 
      .closest('li')  // Go to the closest parent `li` to the img 
      .next('.datalog') // Go to the next sibling of the `li` 
      .hide();    // Show the `ul` with the class `.datalog` 
     } 
    }); 
}); 
相关问题