如何在HTML元素中设置数据属性 [英] How to set data attributes in HTML elements
问题描述
我有一个属性 data-myval =10
的div。我想更新它的价值;如果我使用 div.data('myval',20)
?我需要使用 div.attr('data-myval','20')
吗?
我对HTML5和jQuery感到困惑?请指教。谢谢!
编辑:更新 div.data('myval')= 20
至 div.data('myval',20)
,但仍然没有更新HTML。
HTML
< div id =mydivdata-myval =10> < / DIV>
JS
var a = $('#mydiv')。data('myval'); // getter
$('#mydiv')。data('myval',20); // setter
参考资料 编辑(评论之后): 如果您查看以上给出的参考,说: jQuery本身使用 为什么需要更改html? 如果更改html是绝对必要的,您应该使用 HTML JS: 请参阅本次演示 I have a div with an attribute Am I getting confused between HTML5 and jQuery? Please advise. Thanks! EDIT: Updated HTML JS EDIT (after comment): If you check the reference given above, which says: jQuery itself uses the Why would you need to change html? If changing the html is absolutely necessary, you should use HTML JS: See this demo 这篇关于如何在HTML元素中设置数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
.data()
方法来保存信息名称'事件'和'句柄',并且还保留任何以下划线('_')开头的数据名称供内部使用。
.attr()$ c
< div id =outer>
< div id =mydivdata-myval =10>< / div>
< / div>
alert($('#outer')。html()); //警报< div id =mydivdata-myval =10> < / DIV>
var a = $('#mydiv')。data('myval'); // getter
$('#mydiv')。attr(data-myval,20); // setter
alert($('#outer')。html()); //警报< div id =mydivdata-myval =20> < / DIV>
data-myval = "10"
. I want to update its value; wouldn't it change if I use div.data('myval',20)
? Do I need to use div.attr('data-myval','20')
only?div.data('myval')=20
to div.data('myval',20)
, but still the HTML is not updating.<div id="mydiv" data-myval="10"></div>
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').data('myval',20); //setter
.data()
method to save information under the names 'events' and 'handle', and also reserves any data name starting with an underscore ('_') for internal use..attr()
<div id="outer">
<div id="mydiv" data-myval="10"></div>
</div>
alert($('#outer').html()); // alerts <div id="mydiv" data-myval="10"> </div>
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').attr("data-myval","20"); //setter
alert($('#outer').html()); //alerts <div id="mydiv" data-myval="20"> </div>