2014-10-05 63 views
1

我有一個按字母分組的名稱列表。 示例代碼:JQuery檢查下一個可見元素是否具有相同的類

<label class="alphabet_selector">A</label> 
    <label>Apple</label> 
<label class="alphabet_selector">B</label> 
    <label>Book</label> 
    <label>Baby</label> 
<label class="alphabet_selector">H</label> 
    <label>Help</label> 
    <label>Hello</label> 
    <label>How</label> 
<label class="alphabet_selector">Z</label> 
    <label>Zebra</label> 
    <label>Zip</label> 
    <label>Zoo</label> 

假設開始B所有標籤和Hdisplay: none。 所以<label class="alphabet_selector">B</label><label class="alphabet_selector">H</label>必須隱藏。我怎樣才能實現這個使用jQuery? 我嘗試下面的代碼,但它不工作:

$(".alphabet_selector").each(function() { 
    if ($(this).next(".alphabet_selector").length == 1){ 
     $(this).css("display", "none"); 
    } 
}); 

我覺得因爲.next回報與display: none標籤。

小提琴:http://jsfiddle.net/ff4qh0y7/

+1

'$(本)。接下來( 「alphabet_selector:可見」)' – melancia 2014-10-05 20:28:29

+0

感謝您的評論。但這並不能解決問題。問題是'$(this).next(「。alphabet_selector」)不會返回alphabet_selector。而是返回第一個標籤,它具有'display:none' – Agha 2014-10-05 20:33:23

+0

您的代碼和問題沒有任何意義。你想做什麼? – melancia 2014-10-05 20:35:35

回答

1

可以使用nextAllfirst獲得下一個可見元素並檢查它是否使用is是一個.alphabet_selector

代碼:

$(".alphabet_selector").each(function() { 
    if ($(this).nextAll(":visible").first().is(".alphabet_selector")){ 
     $(this).css("display", "none"); 
    } 
}); 

演示:http://jsfiddle.net/0dff337g/

+0

謝謝。有效! – Agha 2014-10-05 20:49:30

相關問題