jQuery 如何获取、设置和选择具有数据属性的元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13275812/
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-26 12:27:38  来源:igfitidea点击:

How to get, set and select elements with data attributes?

jqueryjquery-selectorscustom-data-attribute

提问by Thaiscorpion

I'm having some trouble with data-attributes, I can't get anything to work for some reason so I must be doing something wrong:

我在数据属性方面遇到了一些问题,由于某种原因我无法进行任何工作,所以我一定是做错了什么:

Set:

放:

$('#element').data('data1', '1'); //Actually in my case the data is been added manually 

Does that make a difference?

这有什么区别吗?

Get:

得到:

$('#element').data('data1');

Select:

选择:

$('#element[data1 = 1]')

None of this works for me, am I making this up or how is it?

这些都不适合我,是我编造的还是怎么回事?

回答by gion_13

All of the answers are correct, but I want to state something that nobody else did.
The jQuery datamethod acts like a getter for html5 data attributes, but the setter does not alter the data-* attribute.
So, If you manually added the data (as is stated in your comment), then you can use a css attribute selector to select your element :

所有的答案都是正确的,但我想说一些其他人没有做过的事情。
jQuerydata方法的作用类似于 html5 数据属性的 getter,但 setter 不会更改 data-* 属性。
因此,如果您手动添加了数据(如您的评论中所述),那么您可以使用 css 属性选择器来选择您的元素:

$('#element[data-data1=1]')  

but if you have added (altered) the data via jQuery, then the above solution won't work.
Here's an example of this failure :

但是如果您通过 jQuery 添加(更改)数据,则上述解决方案将不起作用。
这是此失败的示例:

var div = $('<div />').data('key','value');
alert(div.data('key') == div.attr('data-key'));// it will be false  

So the workaround is to filter the collection by checking the jQuery data value to match the desired one :

因此,解决方法是通过检查 jQuery 数据值以匹配所需的值来过滤集合:

// replace key & value with own strings
$('selector').filter(function(i, el){
    return $(this).data('key') == 'value';
});

So, in order to overcome these issues, you need to use the html5 dataset attributes (via jQuery's attrmethos) as getters and setters :

因此,为了克服这些问题,您需要使用 html5 数据集属性(通过 jQuery 的attr方法)作为 getter 和 setter:

$('selector').attr('data-' + key, value);

or you can use a custom expression that filters jQuery internal data:

或者您可以使用过滤 jQuery 内部的自定义表达式data

$.expr[':'].data = function(elem, index, m) {
    // Remove ":data(" and the trailing ")" from the match, as these parts aren't needed:
    m[0] = m[0].replace(/:data\(|\)$/g, '');
    var regex = new RegExp('([\'"]?)((?:\\\1|.)+?)\1(,|$)', 'g'),
    // Retrieve data key:
    key = regex.exec( m[0] )[2],
    // Retrieve data value to test against:
    val = regex.exec( m[0] );
    if (val) {
        val = val[2];
    }
    // If a value was passed then we test for it, otherwise we test that the value evaluates to true:
    return val ? $(elem).data(key) == val : !!$(elem).data(key);
};

and use it like :

并像这样使用它:

$('selector:data(key,value)')

Update

更新

I know this thread is a few years old, but since it has some activity, it's worth mentioning that doing this using the querySelectordom API (with no need for jQuery) is quite trivial:

我知道这个线程已经有几年的历史了,但是由于它有一些活动,值得一提的是使用querySelectordom API(不需要 jQuery)执行此操作非常简单:

document.querySelectorAll('[attribute=value]')

回答by Sushanth --

To reflect the values of the Attributes immediately in the DOM you can use .attr()

要立即在 DOM 中反映属性的值,您可以使用 .attr()

$('#element').attr('data-data1', '1');  // Sets the attribute

$('#element[data-data1="1"]') // Selects the element with data-data1 attribute'

$('#element').data('data1'); // Gets the value  of the attribute

$('#element').attr('data-data1'); // Gets the value  of the attribute

In plain Javascript you can try this

在普通的 Javascript 中,你可以试试这个

var elem = document.getElementById('element');

elem.setAttribute('data-data1', '1'); // Set the attribute

elem.getAttribute('data-data1'); // Gets the attribute

回答by micadelli

// Set
$('#element').attr('data-value', 'value');
// Get
var value = $('#element').attr('data-value');
// Select
var elem = $('#element[data-value = "' +value+ '"]');

回答by undefined

You are using ID selector so there is no need to use attribute selector, as data is a property and you are setting it using datamethod (not attr method) you cannot select the element using attribute selector, if you want to select the element only if it has data1 === 1you can use the filtermethod:

您正在使用 ID 选择器,因此无需使用属性选择器,因为数据是一个属性,并且您正在使用data方法(而不是 attr 方法)设置它,如果您只想在以下情况下选择元素,则无法使用属性选择器选择元素它有data1 === 1你可以使用的filter方法:

(function($){
    $(function(){
       // ...
       $('#element').filter(function() {
          return this.dataset.data1 == 1
          // return $(this).data('data1') == 1
       })
    })
})(jQuery);

dataset: Allows access, both in reading and writing mode, to all the custom data attributes (data-*) set on the element. It is a map of DOMString, one entry for each custom data attribute.

dataset: 允许在读取和写入模式下访问元素上设置的所有自定义数据属性 (data-*)。它是 DOMString 的映射,每个自定义数据属性一个条目。