jQuery访问当前父元素的子元素

5

我是jQuery的新手,我正在尝试做如下操作:访问当前div的父级的另一个子元素(或者换句话说:当前div的父级的其他子元素)。我的代码看起来像这样(这是我尝试的):

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<script>
$(document).ready(function() {
    $("div.head").click(function() {
        $(this).parent().("div.content").slideToggle("normal"); //<- how?
    });
});
</script>

<div class="box">
<div class="head">
    Example
</div>
<div class="content">
    Content here.
</div>
</div>

我希望这样做是因为这样我可以只用相同的方式制作更多的盒子,而不必添加额外的js使其适用于每个盒子(每个盒子内容的切换隐藏/显示)。
6个回答

6
<script>
$(document).ready(function() {
    $("div.head").click(function() {
        $(this).next("div.content").slideToggle("normal"); //<- easy
    });
});
</script>

谢谢,我没想到这么简单 :D。完美地运行了。 - Jasper vd Berg

4

如果你只关心紧随其后的元素,可以使用happytime harry的解决方案,它使用了.next(),即:

$(this).next(".content").slideToggle("normal");

如果您正在寻找更通用的内容,请使用以下之一:
// Search for elements which are direct children of parent
$(this).parent().children(".content").slideToggle("normal");  

// Search for siblings (same as above, but will not include $(this))
$(this).siblings(".content").slideToggle("normal");

// Search within all descendents of parent
$(this).parent().find(".content").slideToggle("normal");

1
找到坏的:使用children,我们不关心所有后代...兄弟姐妹不好:使用next,我们只关心下一个兄弟姐妹而不是多个。 - mothmonsterman
感谢您整理出的可能方法,这有助于我更好地理解jQuery。 - Jasper vd Berg
非常感谢您,@jasper。祝您使用jQuery好运且愉快。 - Shawn Chin

4
如果这两个元素在同一层级上,那么你可以使用 .siblings() 方法:
$(function() {
    $(".head").click(function() {
        $(this).siblings(".content").slideToggle("normal");
    });
});

这是一个演示:http://jsfiddle.net/L5kqs/1/

您的选择器需要使用.children().find()

$(this).parent().children(".content").slideToggle("normal");

请注意,如果省略标签名称,则选择器的性能将更快。只有当需要搜索大量DOM节点时,才会提高性能。
如果您想了解更多关于.siblings()的信息,可以从这里开始阅读:http://api.jquery.com/siblings

请注意,在IE6中选择器需要标记名称。 - mothmonsterman
@happytimeharry:我很确定没有人关心IE6的支持。 - gen_Eric
@happytimeharry 我刚刚使用带有IE 6的Windows XP虚拟映像进行了测试,没有在选择器中使用标签也可以正常工作。我总是针对IE 6测试我的代码,从来没有省略标签名称的问题。 - Jasper
1
@Jasper 我的错...它是5.5,这是我被迫关注的问题...http://docs.jquery.com/Known_Issues - mothmonsterman
感谢您的回答和额外的解释,对我帮助很大,现在运行得非常好。 - Jasper vd Berg

3

你可以尝试

 $(document).ready(function() {
     $("div.head").click(function() {
         $(this).parent().find(".content").slideToggle("normal"); //<- how?
     });
 });

或者使用同级元素。
 $(this).siblings(".content").slideToggle("normal");

2
你可以使用.children方法来获取div.content
$(document).ready(function() {
    $("div.head").click(function() {
        $(this).parent().children("div.content").slideToggle("normal");
    });
});

或者您可以使用.siblings

$(document).ready(function() {
    $("div.head").click(function() {
        $(this).siblings("div.content").slideToggle("normal");
    });
});

1
找对于他的问题来说是浪费时间...使用子进程。 - mothmonsterman
同意,children 更好 :-) - gen_Eric

0

类似这样的东西应该就够了

$(".head").bind("click", function(){
    $(this).parent().find(".content").slideToggle("normal");
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接