简体   繁体   English

选择最接近的父级jQuery的子级

[英]Selecting child of closest parent jquery

I have the following card header in my view: 我的视图中有以下卡头:

<div class="card-header">
    <div class="media">
        <div class="media-body media-middle">
            <h4 class="card-title">{{ category.name }}</h4>
            <p class="card-subtitle">{{ category.description }}</p>
        </div>
        <div class="media-right media-middle">
            <a href="#" data-toggle="modal" data-target="#addForumPostModal" class="btn btn-white btn-sm add-post-button"><i class="material-icons">add</i></a>
        </div>
    </div>
</div>

I am trying to get the category name when I click on the add-post-button 单击添加后按钮时,我试图获取类别名称

I tried the following jquery but it just printed undefined: 我尝试了以下jQuery,但它只是打印未定义:

$('.add-post-button').on('click', function (){
    console.log($(this).closest('media').children('card-title').html())
});

Use .find() instead of .children() - the latter only looks at immediate children, not grandchildren, etc., whereas .find() looks for descendants at any level. 使用.find()代替.children() -后者只着眼于眼前的孩子,孙子不,等等,而.find()查找在任何级别的后代。

Also, to select by class you need a '.' 另外,要按班级选择,您需要输入'.' before the class name, so '.media' and '.card-title' rather than 'media' and 'card-title' . 在班级名称前加上'.media''.card-title'而不是'media''card-title'

 $('.add-post-button').on('click', function (){ console.log($(this).closest('.media').find('.card-title').html()) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="card-header"> <div class="media"> <div class="media-body media-middle"> <h4 class="card-title">{{ category.name }}</h4> <p class="card-subtitle">{{ category.description }}</p> </div> <div class="media-right media-middle"> <a href="#" data-toggle="modal" data-target="#addForumPostModal" class="btn btn-white btn-sm add-post-button"><i class="material-icons">add</i></a> </div> </div> </div> 

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

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