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

Tha*_*ion 25 jquery jquery-selectors custom-data-attribute

我在使用数据属性方面遇到了一些麻烦,因为某些原因我无法正常工作所以我一定做错了:

组:

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

这有什么区别吗?

得到:

$('#element').data('data1');
Run Code Online (Sandbox Code Playgroud)

选择:

$('#element[data1 = 1]')
Run Code Online (Sandbox Code Playgroud)

这对我来说都不起作用,我是在制作它还是它是什么?

gio*_*_13 55

所有答案都是正确的,但我想陈述其他人没有做过的事情.
jQuery data方法就像html5数据属性的getter一样,但是setter不会改变data-*属性.
因此,如果手动添加数据(如评论中所述),则可以使用css属性选择器选择元素:

$('#element[data-data1=1]')  
Run Code Online (Sandbox Code Playgroud)

但如果您通过jQuery添加(更改)了数据,那么上述解决方案将无效.
以下是此失败的示例:

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

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

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

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

$('selector').attr('data-' + key, value);
Run Code Online (Sandbox Code Playgroud)

或者您可以使用过滤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);
};
Run Code Online (Sandbox Code Playgroud)

并使用它像:

$('selector:data(key,value)')
Run Code Online (Sandbox Code Playgroud)


Sus*_* -- 8

要在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
Run Code Online (Sandbox Code Playgroud)

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

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

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

elem.getAttribute('data-data1'); // Gets the attribute
Run Code Online (Sandbox Code Playgroud)


mic*_*lli 5

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