最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Finding the data attribute value of a parent div several levels up with jQuery - Stack Overflow

programmeradmin5浏览0评论

I am trying to access the nearest div from the anchor tag that has a data-id attribute.

.parent().parent().parent() works but I am really trying to avoid doing that.

<div class="panel panel-default" data-id="@customer.Id">
        <div class="panel-heading clearfix">
            @customer.Name
            <div class="pull-right">
                <a class="btn btn-sm btn-default js-deleteCustomer" href="#" title="Delete">
                    <i class="fa fa-trash" aria-hidden="true"></i>
                </a>
        </div>
</div>

I tried the following:

var customerId = $(this).closest("div:has(*[data-id])").attr('data-id');

I am trying to access the nearest div from the anchor tag that has a data-id attribute.

.parent().parent().parent() works but I am really trying to avoid doing that.

<div class="panel panel-default" data-id="@customer.Id">
        <div class="panel-heading clearfix">
            @customer.Name
            <div class="pull-right">
                <a class="btn btn-sm btn-default js-deleteCustomer" href="#" title="Delete">
                    <i class="fa fa-trash" aria-hidden="true"></i>
                </a>
        </div>
</div>

I tried the following:

var customerId = $(this).closest("div:has(*[data-id])").attr('data-id');
Share Improve this question edited Jul 9, 2017 at 16:55 BoltClock 725k165 gold badges1.4k silver badges1.4k bronze badges asked Jul 9, 2017 at 16:50 Blake RivellBlake Rivell 13.9k33 gold badges130 silver badges261 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

You want

var customerId = $(this).closest("div[data-id]").attr('data-id');

:has(*[data-id]) doesn't match an element with that attribute. It matches an element that contains another element with that attribute. The element that's matched probably doesn't have this same attribute, which would explain why :has(*[data-id]) doesn't work. For instance, it would match the outer div, not the inner div, in the following:

<div>
  <div data-id="@customer.Id"></div>
</div>

To match an element that has an attribute, simply attach the attribute selector directly without using :has().

发布评论

评论列表(0)

  1. 暂无评论