简体   繁体   English

使用jQuery在父容器中查找特定的数据ID

[英]finding a particular data-id in a parent container using jquery

Say if I have the following html: 假设我有以下html:

<a href="some url" class="product-store-name">
    azzaharastore
</a>

and this html is contained inside another div, and another div, of x levels. 并且此html包含在x级别的另一个div和另一个div中。 Is there a way to find the div that has the data-id in it and then get the value of it? 有没有办法找到其中包含数据ID的div,然后获取它的值? In other words I want a function that propates upwards and find the data-id in it. 换句话说,我想要一个向上支撑并在其中找到数据ID的函数。

You can use .closest() along with has attribute selector to find the desired element 您可以使用.closest()has属性选择器来查找所需的元素

if this refers to this element then use(replace this with any other means to refer the target element) 如果this是指该元件然后使用(替换this与任何其他手段来指代目标元件)

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

or for the above said case 或上述情况

var did  = $('.product-store-name').closest('div[data-id]').data('id')

Demo: Fiddle 演示: 小提琴

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

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