繁体   English   中英

定位父级的子级-jQuery

[英]Targeting child of parent - jQuery

我在wordpress中有一系列帖子,每个帖子都有隐藏的部分,单击链接即可显示这些部分。 由于无法正常定位该特定帖子的子级,因此作为普通div引用会使所有隐藏的部分立即显示。

<div class="individual">
    <div class="m-all t-1of4 d-1of4">
        <a class="headshot" href="" style="color: #000 !important">
            <h3>Test</h3>    
        </a>
    </div>
    <div class="desciption-show" style="display: none; background: #ffffff;">
        <div class="m-all t-all d-all cf">
            <h3>Testasdf</h3>
            <h4>Testasdfasdfasdf</h4>
            <p>Testdghjfghjfghj</p>
            <p><em>fghjrtysdfgdfgh</em></p>
            <a class="close" href="">Close</a>
        </div>
    </div>
</div>
$(document).ready(function(){
    $("a.headshot").click(function() {
        $(this).parents(".individual").children('.description-show').show('fast');
    });
});

在Wordpress中,jQuery通常处于无冲突模式,因此您需要一个不同的DOM ready处理程序。

单击锚点时,空的href属性将重新加载页面,因此您可能希望避免这种情况。

closest似乎是一个更好的选择目标的父元素,当被发现的元素停止,其parents没有。

类名有一个错字,应该是description-show ,而不是desciption-show

jQuery(function($){
    $(".headshot").on('click', function(e) {
        e.preventDefault();

        $(this).closest(".individual").children('.description-show').show('fast');
    });
});

小提琴

您可以使用closest()函数定位父对象,然后在父元素中找到子对象,请尝试以下代码

$(document).ready(function(){
    $("a.headshot").click(function(event) {
        event.preventDefault();
        $(this).closest(".individual").children('.desciption-show').show('fast');
    });
});

这是错的

<div class="desciption-show" style="display: none; background: #ffffff;">

因为写错了

$('.description-show')

将div类从desciption-show更改为description-show

另外,我会这样找到我的元素

$(".headshot").click(function (e) {
    e.preventDefault();
        $(this).closest(".individual").find('.description-show').show();
});

这是一个小提琴

希望这可以帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM