[英]Finding the data attribute value of a parent div several levels up with jQuery
I am trying to access the nearest div from the anchor tag that has a data-id attribute. 我正在尝试从具有data-id属性的定位标记访问最近的div。
.parent().parent().parent()
works but I am really trying to avoid doing that. .parent().parent().parent()
可以,但是我实际上是在尝试避免这样做。
<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');
You want 你要
var customerId = $(this).closest("div[data-id]").attr('data-id');
:has(*[data-id])
doesn't match an element with that attribute. :has(*[data-id])
与具有该属性的元素不匹配。 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. 匹配的元素可能没有相同的属性,这可以解释为什么:has(*[data-id])
不起作用。 For instance, it would match the outer div, not the inner div, in the following: 例如,在以下情况下,它将匹配外部div,而不是内部div:
<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()
. 要匹配具有属性的元素,只需直接附加属性选择器,而无需使用:has()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.