.data() documentation中有提到
data-属性在第一次访问数据属性时被拉取,然后不再被访问或改变(所有数据值都存储在jQuery内部)
Why don't changes to jQuery $.fn.data() update the corresponding html 5 data-* attributes? 也对此进行了报道
下面我原始答案的演示似乎不再起作用。
更新答案
再次,来自.data() documentation
在 jQuery 1.6 中更改了对嵌入短划线的属性的处理以符合 W3C HTML5 规范。
所以对于<div data-role="page"></div>,以下是正确的$('div').data('role') === 'page'
我很确定 $('div').data('data-role') 过去曾工作过,但现在似乎不再如此了。我创建了一个更好的展示,它将日志记录到 HTML,而不必打开控制台,并添加了一个额外的多连字符到 camelCase data- attributes 转换的示例。
Updated demo (2015-07-25)
另见jQuery Data vs Attr?
HTML
<div id="changeMe" data-key="luke" data-another-key="vader"></div>
<a href="#" id="changeData"></a>
<table id="log">
<tr><th>Setter</th><th>Getter</th><th>Result of calling getter</th><th>Notes</th></tr>
</table>
JavaScript (jQuery 1.6.2+)
var $changeMe = $('#changeMe');
var $log = $('#log');
var logger;
(logger = function(setter, getter, note) {
note = note || '';
eval('$changeMe' + setter);
var result = eval('$changeMe' + getter);
$log.append('<tr><td><code>' + setter + '</code></td><td><code>' + getter + '</code></td><td>' + result + '</td><td>' + note + '</td></tr>');
})('', ".data('key')", "Initial value");
$('#changeData').click(function() {
// set data-key to new value
logger(".data('key', 'leia')", ".data('key')", "expect leia on jQuery node object but DOM stays as luke");
// try and set data-key via .attr and get via some methods
logger(".attr('data-key', 'yoda')", ".data('key')", "expect leia (still) on jQuery object but DOM now yoda");
logger("", ".attr('key')", "expect undefined (no attr <code>key</code>)");
logger("", ".attr('data-key')", "expect yoda in DOM and on jQuery object");
// bonus points
logger('', ".data('data-key')", "expect undefined (cannot get via this method)");
logger(".data('anotherKey')", ".data('anotherKey')", "jQuery 1.6+ get multi hyphen <code>data-another-key</code>");
logger(".data('another-key')", ".data('another-key')", "jQuery < 1.6 get multi hyphen <code>data-another-key</code> (also supported in jQuery 1.6+)");
return false;
});
$('#changeData').click();
Older demo
原答案
对于这个 HTML:
<div id="foo" data-helptext="bar"></div>
<a href="#" id="changeData">change data value</a>
还有这个 JavaScript(使用 jQuery 1.6.2)
console.log($('#foo').data('helptext'));
$('#changeData').click(function() {
$('#foo').data('helptext', 'Testing 123');
// $('#foo').attr('data-helptext', 'Testing 123');
console.log($('#foo').data('data-helptext'));
return false;
});
See demo
使用Chrome DevTools Console 来检查 DOM,$('#foo').data('helptext', 'Testing 123'); 不会 更新 Console 中看到的值,但是$('#foo').attr('data-helptext', 'Testing 123'); 会。