jQuery通过其data-id获取一个元素

时间:2022-10-09 11:23:31

Similar to this question here, I'm looking to get an element based on it's data-id.

与此问题类似,我希望根据它的data-id获取一个元素。

<a href="#" class="whatever" data-item-id="stand-out">...</a>

......

I'm looking to take action on the a tag. It has a shared class amongst many other elements and has no base id, just a data-item-id.

我想对标签采取行动。它在许多其他元素中有一个共享类,没有基本id,只是一个data-item-id。

Can the element be found by it's data-item-id or can I only find out what the data-item-id is?

可以通过它的data-item-id找到元素,还是只能找出data-item-id是什么?

4 个解决方案

#1


24  

You can always use an attribute selector. The selector itself would look something like:

您始终可以使用属性选择器。选择器本身看起来像:

a[data-item-id=stand-out]

#2


39  

$('[data-item-id="stand-out"]')

$( '[数据项-ID = “待机出”]')

#3


14  

This worked for me, in my case I had a button with a data-id attribute:

这对我有用,在我的例子中,我有一个带有data-id属性的按钮:

$("a").data("item-id");

Fiddle

小提琴

#4


12  

Yes, you can find out element by data attribute.

是的,您可以按数据属性找出元素。

element = $('a[data-item-id="stand-out"]');

#1


24  

You can always use an attribute selector. The selector itself would look something like:

您始终可以使用属性选择器。选择器本身看起来像:

a[data-item-id=stand-out]

#2


39  

$('[data-item-id="stand-out"]')

$( '[数据项-ID = “待机出”]')

#3


14  

This worked for me, in my case I had a button with a data-id attribute:

这对我有用,在我的例子中,我有一个带有data-id属性的按钮:

$("a").data("item-id");

Fiddle

小提琴

#4


12  

Yes, you can find out element by data attribute.

是的,您可以按数据属性找出元素。

element = $('a[data-item-id="stand-out"]');