[英]Toggle specific div based on click, hide all other divs of the same class
在這里查看我當前的代碼: http : //jsfiddle.net/swQLg/3/
我有一些像
<div class="qtn">question1</div>
<div class="ans">answer1</div>
<div class="qtn">question2</div>
<div class="ans">answer2</div>
<div class="qtn">question3</div>
<div class="ans">answer3</div>
<div class="qtn">question4</div>
<div class="ans">answer4</div>
我的jQuery函數是
$(document).ready(function () {
$(".qtn").on('click', function () {
$(this).next(".ans").slideToggle();
});
});
當我顯示一個答案時,如果它們顯示了,我希望它隱藏其他答案。
嘗試這個:
$(document).ready(function () {
$(".qtn").on('click', function () {
var $ans = $(this).next(".ans");
$ans.slideToggle(); //toggle the current one
$(".ans").not($ans).slideUp(); //hide the others
});
});
我保存$(this).next(".ans");
變量是為了性能。 如果我沒有這樣做,那么每次您調用$(this).next(".ans");
是,jQuery將不得不包裹this
成jquery對象,然后執行next()
該jQuery對象上的功能。 在這種情況下,這僅是1個額外的時間,但這仍然意味着2個不必要的操作。
這是一個展示差異的jsperf測試 。
將slideUp()
放入您的click事件中,以使所有內容向上滑動。 這將關閉/隱藏已經打開的div,然后放入您的代碼。
$(document).ready(function () {
$(".qtn").on('click', function () {
$(".ans").not($(this).next(".ans")).slideUp(); // slide the rest up
$(this).next(".ans").slideToggle();
});
});
編輯以修復@smerny指出的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.