$(document).ready( function () {
$("#bla").on( "click", function () {
alert( $(this).data('bla') );
$(this).attr('data-bla', "2");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="bla" data-bla="1">
button
</div>
So, I need change data-bla
value from "1" to "2", but as you can see, value not updated and every click on button, alerts default value "1".
What did I do wrong?
data()
is not an accessor function for data-*
attributes. It's an accessor for jQuery's data cache for the element, which is only initialized from data-*
attributes.
If you want to read the data-bla
attribute's value, use attr("data-bla")
, not data("bla")
. If you want to set the bla
data item, use data("bla", newValue)
, not attr("data-bla", newValue)
.
E.g., use attr()
for both get and set, or use data()
for both get and set, but don't mix them, because they manage different things.
Using attr()
:
$(document).ready( function () {
$("#bla").on( "click", function () {
alert( $(this).attr('data-bla') );
$(this).attr('data-bla', "2");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="bla" data-bla="1">
button
</div>
Using data()
:
$(document).ready( function () {
$("#bla").on( "click", function () {
alert( $(this).data('bla') );
$(this).data('bla', "2");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="bla" data-bla="1">
button
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With