HTML
<div id="mydiv" data-myval="10"></div>
JS
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').data('myval',20); //setter
Demo
Reference
From the reference:
jQuery itself uses the .data()
method to save information under the names 'events' and 'handle', and also reserves any data name starting with an underscore ('_') for internal use.
It should be noted that jQuery's data()
doesn't change the data
attribute in HTML.
So, if you need to change the data
attribute in HTML, you should use .attr()
instead.
HTML
<div id="outer">
<div id="mydiv" data-myval="10"></div>
</div>
?JS:
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>
See this demo
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…