我有一組表示故事類別的div。在每個類別中,都有一個擁有類別頭像的div和一個包含故事摘要的兄弟div。爲什麼jQuery不能切換這個div?
我從隱藏的所有故事div開始,除了包含默認故事的類別;它的故事DIV開始時可見(以下CAT2):
[ cat1 < ]
[ cat2 V ]
- story2-1
- story2-2
[ cat3 < ]
當我點擊任何其他類別的頭,我刪除了「擴大」級,設置對所有類別頭的div向下三角形圖標,隱藏所有的故事div,然後在點擊的類別頭上切換'expanded'類,最後切換故事div,這是所點擊類別頭的兄弟。
所有這些工作正常,如果我點擊一個類別頭其他比當前擴大的。
問題:如果我點擊了當前展開的類頭將其摺疊,所以他們ALL倒塌,沒有任何反應。或者更具體地說,當我記錄結果時,我發現故事div將其'display'屬性設置爲'block',然後立即再次變爲'none'。爲什麼???
代碼
<html>
<head>
<style type="text/css">
.category { width: 200px; }
.category-hed { cursor: pointer; }
.category-hed h2 {
background-image: url(/_img/b/category-hed-arrow-collapsed.gif);
background-repeat: no-repeat;
background-position: center right;
}
.category-hed h2.expanded {
background-image: url(/_img/b/category-hed-arrow-expanded.gif);
}
.category .stories { /* default hidden; clicking category-hed will toggle it */
display: none;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
// set click handlers on the category section headers to expand/collapse the sections
$(".category-hed").click(function() {
$(".category-hed h2").removeClass("expanded"); // unset the 'expanded' indicators in all categories
$(".stories").hide(); // hide the "stories" divs in all categories
// TODO: this doesn't collapse an already-expanded section... why?
$("h2", this).toggleClass("expanded"); // 2nd arg to $() sets context of the selection: h2 under this
$(this).siblings(".stories").toggle(); // show this category's "stories" div
});
// the default story's category section should initially be expanded
var defaultStoryCatID = "#category-2";
$("h2", defaultStoryCatID).toggleClass("expanded");
$(".stories", defaultStoryCatID).show();
});
</script>
</head>
<body>
<div class="category" id="category-1">
<!-- nested H2 below to aid border styling; CSS omitted -->
<div class="category-hed"><h2>Category 1</h2></div>
<div class="stories">
<div class="story">
<h3>cat 1 story1 head</h3>
<p>... the story...</p>
</div>
<div class="story">
<h3>cat 1 story2 head</h3>
<p>... another story...</p>
</div>
</div>
</div>
<div class="category" id="category-2">
<div class="category-hed"><h2>Category 2</h2></div>
<div class="stories">
<div class="story">
<h3>cat 2 story1 head</h3>
<p>... the story...</p>
</div>
<div class="story">
<h3>cat 2 story2 head</h3>
<p>... another story...</p>
</div>
</div>
</div>
<div class="category" id="category-3">
<div class="category-hed"><h2>Category 3</h2></div>
<div class="stories">
<div class="story">
<h3>cat 3 story1 head</h3>
<p>... the story...</p>
</div>
<div class="story">
<h3>cat 3 story2 head</h3>
<p>... another story...</p>
</div>
</div>
</div>
</body>
</html>
Doh,額外的div是一個代碼 - 清理錯誤 - 我應該看到,因爲故事div是category-hed div的一個* sibling *,而不是一個孩子,修正了你重新排序的click函數的效果 - 謝謝!!! – Val 2010-12-09 19:14:14