2017-06-14 46 views
0

know如何在知道類名時隱藏除類的第一個實例以外的所有類,但是如何在類爲動態時完成此類動作。 例如:使用jQuery隱藏所有動態類的第一個實例

<div class="staticcontainername"> 
    <div class="variable"></div> <!-- This should show --> 
    <div class="variable"></div> 
    <div class="variable"></div> 
    <div class="variable2"></div> <!-- This should show --> 
    <div class="variable2"></div> 
    <div class="variable3"></div> <!-- This should show --> 
    <div class="variable3"></div> 
    <div class="variable3"></div> 
</div> 

只有每3周的div的第一次應該是可見的,不管是什麼類成爲或有多少項目的存在。

+0

所以,現在你的編輯之後,你只想要顯示的容器中的每個新類的第一個實例 - 是正確的? –

+0

是的,只顯示每個類的第一個實例,不管類名或數量如何 – Sam

回答

0

使用JavaScript

您可以在它們之間迭代,並與前一個比較級。 只有當類完全匹配時纔會起作用,因此如果您有一個具有額外類的div,則會被視爲「不同」。

$(function() { 
 
    var previousClass; 
 
    $('.staticcontainername div').each(function(index) { 
 
    // loop trough all elements in the container and get the class of the current element 
 
    var currentClass = $(this).attr('class'); 
 

 
    // compare the elements class with the previous one. 
 
    // if it matches, hide it 
 
    if (currentClass === previousClass) { 
 
     $(this).hide(); 
 
    } 
 

 
    // before we go to the next element, update the previousClass 
 
    // so we can compare it in the next iteration 
 
    previousClass = currentClass; 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script> 
 
<div class="staticcontainername"> 
 
    <div class="variable">1</div> 
 
    <!-- This should show --> 
 
    <div class="variable">2</div> 
 
    <div class="variable">3</div> 
 
    <div class="variable2">1</div> 
 
    <!-- This should show --> 
 
    <div class="variable2">2</div> 
 
    <div class="variable3">1</div> 
 
    <!-- This should show --> 
 
    <div class="variable3">2</div> 
 
    <div class="variable3">3</div> 
 
</div>

純CSS

如果你知道一個可能出現的可能的類,你可以使用CSS,只顯示第一個。正如pointed out in this answer那樣,沒有像「第一堂課」那樣的選擇器。然而,提供了一個很好的解決方法,我們可以改變這種情況。

.staticcontainername>.variable~.variable, 
 
.staticcontainername>.variable2~.variable2, 
 
.staticcontainername>.variable3~.variable3 { 
 
    display: none; 
 
}
<div class="staticcontainername"> 
 
    <div class="variable">1</div> 
 
    <!-- This should show --> 
 
    <div class="variable">2</div> 
 
    <div class="variable">3</div> 
 
    <div class="variable2">1</div> 
 
    <!-- This should show --> 
 
    <div class="variable2">2</div> 
 
    <div class="variable3">1</div> 
 
    <!-- This should show --> 
 
    <div class="variable3">2</div> 
 
    <div class="variable3">3</div> 
 
</div>

+0

類名稱只是替代任何結構後面的動態類的替代品,所以我不相信純粹的CSS解決方案可行。 – Sam

+0

@Sam這就是爲什麼我開始使用智慧「如果你知道可能的類」,這可能是一個定義的集合。在這一點上我們不知道;) – JasperZelf

相關問題