jQuery 通过其数据 ID 获取元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19866509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:44:24  来源:igfitidea点击:

jQuery get an element by its data-id

javascriptjquery

提问by MacSalty

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

类似于这里的这个问题,我希望根据它的数据 ID 获取一个元素。

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

<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.

我希望对 a 标签采取行动。它在许多其他元素中有一个共享类,并且没有基本 id,只有一个数据项 id。

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

元素可以通过它的数据项 ID 找到还是我只能找出数据项 ID 是什么?

回答by kumarharsh

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

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

回答by Justin Niessner

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

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

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

回答by kd12

Yes, you can find out element by data attribute.

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

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

回答by Tahir Khalid

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

这对我有用,就我而言,我有一个带有 data-id 属性的按钮:

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

Fiddle

小提琴