2013-07-23 42 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` 
     } 
    }); 
}); 
相關問題