无法访问层次结构中的特定元素

时间:2012-06-15 22:31:33

标签: jquery

我无法直接使用$(' commentbody')因为有很多评论和选择需要针对此特定区域进行。

HTML:

<div class="commentline">
    <div class="carrowholder">
        <div class="ctoggle"></div>
        <div class="arrowwrap">
        </div>
    </div>
    <div class="commentholder">
        <div class="commenttitle">
            Title
        </div>
        <div class="commentbody">
            Body
        </div>
    </div>
</div>

jQuery的:

$('.ctoggle').click(function(e) {
    $(this).parent().next('.commentholder > .commentbody').hide();
})

4 个答案:

答案 0 :(得分:2)

您的尝试失败,因为您正在寻找与选择器匹配的父元素的兄弟

.commentholder > .commentbody

没有兄弟会与之相匹配(.commentholder是兄弟姐妹,但你正在寻找一个孩子),所以你需要将子选择器移出。您可以使用children(或find):

$('.ctoggle').click(function(e) {
    $(this).parent().next().children('.commentbody').hide();
});

答案 1 :(得分:0)

$('.ctoggle').click(function(e) {
    $(this).parent().next().find('.commentbody').hide();
})

答案 2 :(得分:0)

从API文档:“获取匹配元素集中每个元素的紧随其后的兄弟。如果提供了一个选择器,它只检查下一个兄弟,只要它匹配那个选择器。”

所以,你的选择器匹配兄弟姐妹的孩子,你将不会得到任何东西。尝试:

var x = $(this).parent().next('.commentholder');
x.find('.commentbody').hide();

(这适用于您的示例)

答案 3 :(得分:0)

给出以下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的父元素),然后它在该分支中找到所有元素具有类.commentbody的DOM树,在这种情况下很好,因为每个注释行只有一个注释对象。如果每个.commentbody DIV中有更多.commentline个DIV,那么您需要进一步指定哪一个(再次使用.first().find()等。)

已经提到了其他解决方案,但我发现这种方法更具可读性,因此可维护 - 但这是我的观点:O)