我有一組網格排列的div。如何使用jQuery detach()方法將元素切入和切出DOM?
款式每格我與nth-child()
pseudo-class選擇它們。
div.tile:nth-child(4n-7) .text { background-color: yellow; }
用戶可以通過點擊按鈕(其觸發一個jQuery函數,增加了一個display: none
規則到class
屬性在選定DIV)隱藏的div。
jQuery的
$('.hide-divs').click(function() {
$('.dolphin').toggleClass('hidden');
})
CSS
.hidden { display: none; }
這裏的問題:
即使display: none
從屏幕移開的股利,它不會刪除從DOM的div,所以nth-child
選擇器在應用樣式時仍會對其進行計數,這樣會擾亂網格的視覺設計。
上述佈局被打破,因爲只有第一列應爲黃色。
所以我的第一個想法是使用jQuery remove()
method,它將元素(及其後代)帶出DOM。
原來,但是,一旦remove()
應用,你不能得到這些div回來。他們走了。因此切換功能中斷。
經過一番研究,我發現jQuery detach()
method與.remove()
的功能完全相同,只是它存儲了已刪除元素的數據供以後使用。
.detach()
的方法是相同的.remove()
,不同之處在於.detach()
保持與除去 元件相關聯的所有的jQuery的數據。如果刪除的元素將在稍後重新插入到DOM中,此方法非常有用。
一切看起來不錯detach()
與切換開關一起工作,除了我的努力實施它是行不通的。
我用example on the jQuery website作爲指南,但它不適用於電網。我也讀過這個網站上的各種相關帖子,但無濟於事。我肯定錯過了什麼。
任何反饋將不勝感激。
$('.hide-divs').click(function() {
$('.dolphin').toggleClass('hidden');
})
.row {
display: flex;
flex-wrap: wrap;
width: 500px;
padding: 0;
margin: 0;
}
.text {
height: 50px;
width: 100px;
margin: 10px;
padding-top: 15px;
background: tomato;
color: #fff;
text-align: center;
font-size: 2em;
}
.tile:nth-child(4n-7) .text {
border: 2px solid #ccc;
background-color: yellow;
color: #000;
}
button {
padding: 10px;
background-color: lightblue;
position: relative;
left: 200px;
}
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="tile">
<div class="text">01</div>
</div>
<div class="tile">
<div class="text">02</div>
</div>
<div class="tile">
<div class="text dolphin">03</div>
</div>
<div class="tile">
<div class="text">04</div>
</div>
<div class="tile">
<div class="text">05</div>
</div>
<div class="tile">
<div class="text dolphin">06</div>
</div>
<div class="tile">
<div class="text">07</div>
</div>
<div class="tile">
<div class="text dolphin">08</div>
</div>
<div class="tile">
<div class="text">09</div>
</div>
<div class="tile">
<div class="text">10</div>
</div>
<div class="tile">
<div class="text">11</div>
</div>
<div class="tile">
<div class="text">12</div>
</div>
</div><!-- end .row -->
<button type="button" class="hide-divs">HIDE DIVS 3, 6 & 8</button>
這實際上並不奏效。如果您嘗試隱藏其他div,則佈局會中斷。 http://jsfiddle.net/tfyfpbb2/2/ ..另外,它不會從DOM中刪除隱藏的元素。不管怎麼說,還是要謝謝你。 –