使用 jQuery 按数据属性选择元素

发布于 2024-08-26 17:43:02 字数 179 浏览 10 评论 0原文

是否有一种简单直接的方法来根据元素的 data 属性来选择元素?例如,选择具有名为 customerID 的数据属性(其值为 22)的所有锚点。

我有点犹豫是否使用 rel 或其他属性来存储此类信息,但我发现根据存储在其中的数据来选择元素要困难得多。

Is there an easy and straight-forward method to select elements based on their data attribute? For example, select all anchors that has data attribute named customerID which has value of 22.

I am kind of hesitant to use rel or other attributes to store such information, but I find it much harder to select an element based on what data is stored in it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

苍暮颜 2024-09-02 17:43:02
$('*[data-customerID="22"]');

您应该能够省略 *,但如果我没记错的话,根据您使用的 jQuery 版本,这可能会产生错误的结果。

请注意,为了与 Selectors API (document.querySelector{,all}) 兼容,属性值周围的引号 (22) 在这种情况下不能省略

另外,如果您在 jQuery 脚本中经常使用数据属性,您可能需要考虑使用 HTML5 自定义数据属性插件。这允许您使用 .dataAttr('foo') 编写更具可读性的代码,并在缩小后产生更小的文件大小(与使用 .attr('data-foo' 相比) ))。

$('*[data-customerID="22"]');

You should be able to omit the *, but if I recall correctly, depending on which jQuery version you’re using, this might give faulty results.

Note that for compatibility with the Selectors API (document.querySelector{,all}), the quotes around the attribute value (22) may not be omitted in this case.

Also, if you work with data attributes a lot in your jQuery scripts, you might want to consider using the HTML5 custom data attributes plugin. This allows you to write even more readable code by using .dataAttr('foo'), and results in a smaller file size after minification (compared to using .attr('data-foo')).

迷乱花海 2024-09-02 17:43:02

对于通过谷歌搜索并想要使用数据属性进行选择的更通用规则的人:

$("[data-test]") 将选择仅具有数据属性的任何元素(无论属性的值如何)。包括:

<div data-test=value>attributes with values</div>
<div data-test>attributes without values</div>

$('[data-test~="foo"]') 将选择数据属性包含但不包含 foo 的任何元素不必精确,例如:

<div data-test="foo">Exact Matches</div>
<div data-test="this has the word foo">Where the Attribute merely contains "foo"</div>

$('[data-test="the_exact_value"]') 将选择数据属性精确值为 the_exact_value 的任何元素,例如:

<div data-test="the_exact_value">Exact Matches</div>

但不是

<div data-test="the_exact_value foo">This won't match</div>

For people Googling and want more general rules about selecting with data-attributes:

$("[data-test]") will select any element that merely has the data attribute (no matter the value of the attribute). Including:

<div data-test=value>attributes with values</div>
<div data-test>attributes without values</div>

$('[data-test~="foo"]') will select any element where the data attribute contains foo but doesn't have to be exact, such as:

<div data-test="foo">Exact Matches</div>
<div data-test="this has the word foo">Where the Attribute merely contains "foo"</div>

$('[data-test="the_exact_value"]') will select any element where the data attribute exact value is the_exact_value, for example:

<div data-test="the_exact_value">Exact Matches</div>

but not

<div data-test="the_exact_value foo">This won't match</div>
初相遇 2024-09-02 17:43:02

使用 $('[data-whatever="myvalue"]') 将选择具有 html 属性的任何内容,但在较新的 jQueries 中,似乎如果您使用 $(...).data (...) 附加数据,它使用一些神奇的浏览器东西并且不会影响 html,因此不会被 .find 发现,如 上一个答案

验证(使用 1.7.2+ 进行测试)(另请参阅 fiddle):(更新为更完整)

var $container = $('<div><div id="item1"/><div id="item2"/></div>');

// add html attribute
var $item1 = $('#item1').attr('data-generated', true);

// add as data
var $item2 = $('#item2').data('generated', true);

// create item, add data attribute via jquery
var $item3 = $('<div />', {id: 'item3', data: { generated: 'true' }, text: 'Item 3' });
$container.append($item3);

// create item, "manually" add data attribute
var $item4 = $('<div id="item4" data-generated="true">Item 4</div>');
$container.append($item4);

// only returns $item1 and $item4
var $result = $container.find('[data-generated="true"]');

Using $('[data-whatever="myvalue"]') will select anything with html attributes, but in newer jQueries it seems that if you use $(...).data(...) to attach data, it uses some magic browser thingy and does not affect the html, therefore is not discovered by .find as indicated in the previous answer.

Verify (tested with 1.7.2+) (also see fiddle): (updated to be more complete)

var $container = $('<div><div id="item1"/><div id="item2"/></div>');

// add html attribute
var $item1 = $('#item1').attr('data-generated', true);

// add as data
var $item2 = $('#item2').data('generated', true);

// create item, add data attribute via jquery
var $item3 = $('<div />', {id: 'item3', data: { generated: 'true' }, text: 'Item 3' });
$container.append($item3);

// create item, "manually" add data attribute
var $item4 = $('<div id="item4" data-generated="true">Item 4</div>');
$container.append($item4);

// only returns $item1 and $item4
var $result = $container.find('[data-generated="true"]');
肩上的翅膀 2024-09-02 17:43:02

我还没有看到没有 jQuery 的 JavaScript 答案。希望它能帮助某人。

var elements = document.querySelectorAll('[data-customerID="22"]');

elements[0].innerHTML = 'it worked!';
<a data-customerID='22'>test</a>

信息:

I haven't seen a JavaScript answer without jQuery. Hopefully it helps someone.

var elements = document.querySelectorAll('[data-customerID="22"]');

elements[0].innerHTML = 'it worked!';
<a data-customerID='22'>test</a>

Info:

提笔书几行 2024-09-02 17:43:02

要选择具有数据属性 data-customerID==22 的所有锚点,您应该包含 a 以将搜索范围限制为仅该元素类型。当页面上有很多元素时,以大循环或高频率执行数据属性搜索可能会导致性能问题。

$('a[data-customerID="22"]');

To select all anchors with the data attribute data-customerID==22, you should include the a to limit the scope of the search to only that element type. Doing data attribute searches in a large loop or at high frequency when there are many elements on the page can cause performance issues.

$('a[data-customerID="22"]');
北方。的韩爷 2024-09-02 17:43:02

原生 JS 示例

获取元素的 NodeList

var elem = document.querySelectorAll('[data-id="container"]')

html:

获取第一个元素

var firstElem = document.querySelector('[id="container"]')

html:

定位返回节点列表的节点集合

document.getElementById('footer').querySelectorAll('[data-id]')

html:

<div class="footer">
    <div data-id="12"></div>
    <div data-id="22"></div>
</div>

获取基于以下内容的元素多个(OR)数据值

document.querySelectorAll('[data-section="12"],[data-selection="20"]')

html:

<div data-selection="20"></div>
<div data-section="12"></div>

根据组合(AND)数据值获取元素

document.querySelectorAll('[data-prop1="12"][data-prop2="20"]')

html:

<div data-prop1="12" data-prop2="20"></div>

获取值开头的项目

document.querySelectorAll('[href^="https://"]')

Native JS Examples

Get NodeList of elements

var elem = document.querySelectorAll('[data-id="container"]')

html: <div data-id="container"></div>

Get the first element

var firstElem = document.querySelector('[id="container"]')

html: <div id="container"></div>

Target a collection of nodes which returns a nodelist

document.getElementById('footer').querySelectorAll('[data-id]')

html:

<div class="footer">
    <div data-id="12"></div>
    <div data-id="22"></div>
</div>

Get elements based on multiple (OR) data values

document.querySelectorAll('[data-section="12"],[data-selection="20"]')

html:

<div data-selection="20"></div>
<div data-section="12"></div>

Get elements based on combined (AND) data values

document.querySelectorAll('[data-prop1="12"][data-prop2="20"]')

html:

<div data-prop1="12" data-prop2="20"></div>

Get items where the value starts with

document.querySelectorAll('[href^="https://"]')
So尛奶瓶 2024-09-02 17:43:02

通过 Jquery filter() 方法:

http://jsfiddle.net/9n4e1agn/1/

HTML:

<button   data-id='1'>One</button>
<button   data-id='2'>Two</button>

JavaScript:

$(function() {    
    $('button').filter(function(){
        return $(this).data("id")   == 2}).css({background:'red'});  
     });

via Jquery filter() method:

http://jsfiddle.net/9n4e1agn/1/

HTML:

<button   data-id='1'>One</button>
<button   data-id='2'>Two</button>

JavaScript:

$(function() {    
    $('button').filter(function(){
        return $(this).data("id")   == 2}).css({background:'red'});  
     });
仲春光 2024-09-02 17:43:02

像这样的结构:$('[data-XXX=111]')Safari 8.0 中不起作用。

如果您这样设置数据属性:$('div').data('XXX', 111),则只有直接在 DOM 中设置数据属性才有效:$( 'div').attr('data-XXX', 111).

我认为这是因为 jQuery 团队优化了垃圾收集器,以防止内存泄漏和每个更改数据属性上的 DOM 重建的繁重操作。

The construction like this: $('[data-XXX=111]') isn't working in Safari 8.0.

If you set data attribute this way: $('div').data('XXX', 111), it only works if you set data attribute directly in DOM like this: $('div').attr('data-XXX', 111).

I think it's because jQuery team optimized garbage collector to prevent memory leaks and heavy operations on DOM rebuilding on each change data attribute.

七七 2024-09-02 17:43:02

要使其在 Chrome 中发挥作用,该值必须不能有另一对引号。

它只能工作,例如,像这样:

$('a[data-customerID=22]');

For this to work in Chrome the value must not have another pair of quotes.

It only works, for example, like this:

$('a[data-customerID=22]');
迷离° 2024-09-02 17:43:02

有时需要根据元素是否以编程方式附加数据项来过滤元素(也称为不通过 dom 属性):

$el.filter(function(i, x) { return $(x).data('foo-bar'); }).doSomething();

上面的方法可以工作,但可读性不是很好。更好的方法是使用伪选择器来测试此类事情:

$.expr[":"].hasData = $.expr.createPseudo(function (arg) {
    return function (domEl) {
        var $el = $(domEl);
        return $el.is("[" + ((arg.startsWith("data-") ? "" : "data-") + arg) + "]") || typeof ($el.data(arg)) !== "undefined";
    };
});

现在我们可以将原始语句重构为更流畅和可读的内容:

$el.filter(":hasData('foo-bar')").doSomething();

It's sometimes desirable to filter elements based on whether they have data-items attached to them programmatically (aka not via dom-attributes):

$el.filter(function(i, x) { return $(x).data('foo-bar'); }).doSomething();

The above works but is not very readable. A better approach is to use a pseudo-selector for testing this sort of thing:

$.expr[":"].hasData = $.expr.createPseudo(function (arg) {
    return function (domEl) {
        var $el = $(domEl);
        return $el.is("[" + ((arg.startsWith("data-") ? "" : "data-") + arg) + "]") || typeof ($el.data(arg)) !== "undefined";
    };
});

Now we can refactor the original statement to something more fluent and readable:

$el.filter(":hasData('foo-bar')").doSomething();
空袭的梦i 2024-09-02 17:43:02

只是为了用“生活标准”的一些功能来完成所有答案 - 到目前为止(在 html5 时代)无需第三方库就可以做到这一点:

  • 带有 querySelector 的纯/纯 JS(使用 CSS 选择器):
    • 选择 DOM 中的第一个:document.querySelector('[data-answer="42"],[type="submit"]')
    • 选择 DOM 中的所有内容:document.querySelectorAll('[data-answer="42"],[type="submit"]')
  • 纯 CSS
    • 一些特定标签:[data-answer="42"],[type="submit"]
    • 具有特定属性的所有标签:[data-answer]input[type]

Just to complete all the answers with some features of the 'living standard' - By now (in the html5-era) it is possible to do it without an 3rd party libs:

  • pure/plain JS with querySelector (uses CSS-selectors):
    • select the first in DOM: document.querySelector('[data-answer="42"],[type="submit"]')
    • select all in DOM: document.querySelectorAll('[data-answer="42"],[type="submit"]')
  • pure/plain CSS
    • some specific tags: [data-answer="42"],[type="submit"]
    • all tags with an specific attribute: [data-answer] or input[type]
梦一生花开无言 2024-09-02 17:43:02

它会起作用:)

$('.ic-star[data-rate="1"]').addClass('erated');

It will work :)

$('.ic-star[data-rate="1"]').addClass('rated');

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文