问题
I have a div with an attribute 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?
Am I getting confused between HTML5 and jQuery? Please advise. Thanks!
EDIT: Updated div.data(\'myval\')=20 to div.data(\'myval\',20), but still the HTML is not updating.
回答1:
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
回答2:
You can also use the following attr thing;
HTML
<div id="mydiv" data-myval="JohnCena"></div>
Script
$('#mydiv').attr('data-myval', 'Undertaker'); // sets
$('#mydiv').attr('data-myval'); // gets
OR
$('#mydiv').data('myval'); // gets value
$('#mydiv').data('myval','John Cena'); // sets value
回答3:
Please take note that jQuery .data() is not updated when you change html5 data- attributes with javascript.
If you use jQuery .data() to set data- attributes in HTML elements you better use jQuery .data() to read them. Otherwise there can be inconsistencies if you update the attributes dynamically. For example, see setAttribute(), dataset(), attr() below. Change the value, push the button several times and see the console.
$("#button").on("click", function() {
var field = document.querySelector("#textfield")
switch ($("#method").val()) {
case "setAttribute":
field.setAttribute("data-customval", field.value)
break;
case "dataset":
field.dataset.customval = field.value
break;
case "jQuerydata":
$(field).data("customval", field.value)
break;
case "jQueryattr":
$(field).attr("data-customval", field.value)
break;
}
objValues = {}
objValues['$(field).data("customval")'] = $(field).data("customval")
objValues['$(field).attr("data-customval")'] = $(field).attr("data-customval")
objValues['field.getAttribute("data-customval")'] = field.getAttribute("data-customval")
objValues['field.dataset.customval'] = field.dataset.customval
console.table([objValues])
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1>Example</h1>
<form>
<input id="textfield" type="text" data-customval="initial">
<br/>
<input type="button" value="Set and show in console.table (F12)" id="button">
<br/>
<select id="method">
<option value="setAttribute">setAttribute</option>
<option value="dataset">dataset</option>
<option value="jQuerydata">jQuery data</option>
<option value="jQueryattr">jQuery attr</option>
</select>
<div id="results"></div>
</form>
回答4:
Vanilla Javascript solution
HTML
<div id="mydiv" data-myval="10"></div>
JavaScript:
Using DOM's getAttribute() property
var brand = mydiv.getAttribute("data-myval")//returns "10" mydiv.setAttribute("data-myval", "20") //changes "data-myval" to "20" mydiv.removeAttribute("data-myval") //removes "data-myval" attribute entirelyUsing JavaScript's dataset property
var myval = mydiv.dataset.myval //returns "10" mydiv.dataset.myval = '20' //changes "data-myval" to "20" mydiv.dataset.myval = null //removes "data-myval" attribute
回答5:
If you're using jQuery, use .data():
div.data('myval', 20);
You can store arbitrary data with .data(), but you're restricted to just strings when using .attr().
回答6:
[jQuery] .data() vs .attr() vs .extend()
The jQuery method .data() updates an internal object managed by jQuery through the use of the method, if I'm correct.
If you'd like to update your data-attributes with some spread, use --
$('body').attr({ 'data-test': 'text' });
-- otherwise, $('body').attr('data-test', 'text'); will work just fine.
Another way you could accomplish this is using --
$.extend( $('body')[0].dataset, { datum: true } );
-- which restricts any attribute change to HTMLElement.prototype.dataset, not any additional HTMLElement.prototype.attributes.
回答7:
Another way to set the data- attribute is using the dataset property.
<div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe</div>
const el = document.querySelector('#user');
// el.id == 'user'
// el.dataset.id === '1234567890'
// el.dataset.user === 'johndoe'
// el.dataset.dateOfBirth === ''
// set the data attribute
el.dataset.dateOfBirth = '1960-10-03';
// Result: el.dataset.dateOfBirth === 1960-10-03
delete el.dataset.dateOfBirth;
// Result: el.dataset.dateOfBirth === undefined
// 'someDataAttr' in el.dataset === false
el.dataset.someDataAttr = 'mydata';
// Result: 'someDataAttr' in el.dataset === true
来源:https://stackoverflow.com/questions/13524107/how-to-set-data-attributes-in-html-elements