简体   繁体   English

无法使用 jQuery 获取远程父 div 中的元素

[英]Cannot get element inside distant parent div using jQuery

In a dom which has many of the blocks like the one below, I'd like to get name of pid element (id 123 ) when link is clicked:在具有许多块的 dom 中,如下所示,我想在单击link时获取pid元素的名称(id 123 ):

<div class="a-post">
    <a class="pid" name="123"></a>
    <div class="row">
        <p>Some text</p>
    </div>
    <br>
    <div class="row">
        <div class="col-xs-12">
            <p>Othe text </p>
        </div>

        <br>
        <div class="row">
            <div class="col-xs-1">
                <img class="link" src="link.svg">
            </div>

        </div>

    </div>
</div>

Here is my jQuery:这是我的 jQuery:

$(document).ready(function () {
  $(".link").click(function () {
    let pid = $(this).parent(".a-post").find(".pid").attr('name');
    console.log('pid is:', pid);
 }
});

But I get pid is: undefined但我得到的pid is: undefined

How can I fix this?我怎样才能解决这个问题?

You have to use .closest() and not .parent() , because .parent() only goes 1 step up.您必须使用.closest()而不是.parent() ,因为.parent()只会上升.parent() .closest() will continue until it reach the top or finds the element. .closest()将继续直到它到达顶部或找到元素。

 $(document).ready(function() { $(".link").click(function() { let pid = $(this).closest(".a-post").find(".pid").attr('name'); console.log('pid is:', pid); }) })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="a-post"> <a class="pid" name="123"></a> <div class="row"> <p>Some text</p> </div> <br> <div class="row"> <div class="col-xs-12"> <p>Othe text </p> </div> <br> <div class="row"> <div class="col-xs-1"> <img class="link" src="link.svg"> </div> </div> </div> </div>

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

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