給出下面的HTML:
<!DOCTYPE html>
<html>
<head>
[include jQuery here]
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
</head>
<body>
<div class="commentline">
<div class="carrowholder">
<div class="ctoggle">Click to toggle</div>
<div class="arrowwrap">
</div>
</div>
<div class="commentholder">
<div class="commenttitle">
Title 1
</div>
<div class="commentbody">
Body 1
</div>
</div>
<div class="commentline">
<div class="carrowholder">
<div class="ctoggle">Click to toggle</div>
<div class="arrowwrap">
</div>
</div>
<div class="commentholder">
<div class="commenttitle">
Title 2
</div>
<div class="commentbody">
Body 2
</div>
</div>
</div>
</body>
</html>
這個Javascript將工作:
$('.ctoggle').click(function(e) {
$(this).closest('.commentline').find('.commentbody').toggle();
});
這樣做有什麼發現DOM中的第一個元素,其類別爲.commentline
(這是所有DIV的父類) nt),然後它找到所有類型爲.commentbody
的DOM樹的下一個元素,這在這種情況下很好,因爲每個註釋行只有一個註釋體。如果在每個.commentline
DIV中還有更多.commentbody
DIV,那麼您需要進一步指定哪一個(再次使用.first()
或.find()
等)。
已經有提到的其他解決方案,但我覺得這樣的做法要稍微更具可讀性,從而維護 - 但這是我的意見:O)
好,你將必須有唯一的ID爲divs,如果你想訪問他們唯一。 – FlavorScape
Duplicate: http://stackoverflow.com/questions/11058645/jquery-event-of-replaced-class – 2012-06-15 22:34:01
@Geoist我把問題分成兩部分,因爲問題是不同的。 – DavidW