无法更新数据属性值

尽管在网上有一些这样的例子,但它似乎不能正确地工作。我想不出问题所在。

我有这个简单的 HTML

<div id="foo" data-num="0"></ div>
<a href="#" id="changeData">change data value</a>

每次我点击链接“更改数据值”我想更新的数据值的 data-num。 例如,我需要它是1,2,3,4,... (每次单击链接时加1)

我所拥有的是

var num = $('#foo').data("num");
console.log(num);
num = num+1;
console.log(num);
$('#foo').attr('data-num', num);

该值每次从0变化一次为1。我不能让它增量。对于我做错了什么有什么建议吗?

218699 次浏览

THE ANSWER BELOW IS THE GOOD ONE

You aren't using the data method correctly. The correct code to update data is:

$('#foo').data('num', num);

So your example would be:

var num = $('#foo').data("num") + 1;
console.log(num)
$('#foo').data('num', num);
console.log(num)

Use that instead, if you wish to change the attribute data-num of node element, not of data object:

DEMO

$('#changeData').click(function (e) {
e.preventDefault();
var num = +$('#foo').attr("data-num");
console.log(num);
num = num + 1;
console.log(num);
$('#foo').attr('data-num', num);
});

PS: but you should use the data() object in virtually all cases, but not all...

If we wanted to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute and setAttribute methods as shown below:

JavaScript

<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'


// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit','7'); // Pesky birds
</script>

Through jQuery

// Fetching data
var fruitCount = $(this).data('fruit');


// Above does not work in firefox. So use below to get attribute value.
var fruitCount = $(this).attr('data-fruit');


// Assigning data
$(this).data('fruit','7');


// But when you get the value again, it will return old value.
// You have to set it as below to update value. Then you will get updated value.
$(this).attr('data-fruit','7');

Read this documentation for vanilla js or this documentation for jquery

For myself, using Jquery lib 2.1.1 the following did NOT work the way I expected:

Set element data attribute value:

$('.my-class').data('num', 'myValue');
console.log($('#myElem').data('num'));// as expected = 'myValue'

BUT the element itself remains without the attribute:

<div class="my-class"></div>

I needed the DOM updated so I could later do $('.my-class[data-num="myValue"]') //current length is 0

So I had to do

$('.my-class').attr('data-num', 'myValue');

To get the DOM to update:

<div class="my-class" data-num="myValue"></div>

Whether the attribute exists or not $.attr will overwrite.

This answer is for those seeking to just change the value of a data-attribute

The suggested will not change the value of your Jquery data-attr correctly as @adeneo has stated. For some reason though, I'm not seeing him (or any others) post the correct method for those seeking to update their data-attr. The answer that @Lucas Willems has posted may be the answer to problem Brian Tompsett - 汤莱恩 is having, but it's not the answer to the inquiry that may be bringing other users here.

Quick answer in regards to original inquiry statement

-To update data-attr

$('#ElementId').attr('data-attributeTitle',newAttributeValue);

Easy mistakes* - there must be "data-" at the beginning of your attribute you're looking to change the value of.

Had similar problem and in the end I had to set both

obj.attr('data-myvar','myval')

and

obj.data('myvar','myval')

And after this

obj.data('myvar') == obj.attr('data-myvar')

Hope this helps.

Had a similar problem, I propose this solution althought is not supported in IE 10 and under.

Given

<div id='example' data-example-update='1'></div>

The Javascript standard defines a property called dataset to update data-example-update.

document.getElementById('example').dataset.exampleUpdate = 2;

Note: use camel case notation to access the correct data attribute.

Source: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

Basically, there are two ways to set / update data attribute value, depends on your need. The difference is just, where the data saved,

If you use .data() it will be saved in local variable called data_user, and its not visible upon element inspection, If you use .attr() it will be publicly visible.

Much clearer explanation on this comment

I had the same problem of the html data tag not updating when i was using jquery But changing the code that does the actual work from jquery to javascript worked.

Try using this when the button is clicked: (Note that the main code is Javascripts setAttribute() function.)

function increment(q) {


//increment current num by adding with 1
q = q+1;


//change data attribute using JS setAttribute function
div.setAttribute('data-num',q);


//refresh data-num value (get data-num value again using JS getAttribute function)
num = parseInt(div.getAttribute('data-num'));


//show values
console.log("(After Increment) Current Num: "+num);


}


//get variables, set as global vars
var div = document.getElementById('foo');
var num = parseInt(div.getAttribute('data-num'));


//increment values using click
$("#changeData").on('click',function(){


//pass current data-num as parameter
increment(num);


});