jQuery 无法更新数据属性值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17762906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can't update data-attribute value
提问by dev
Although there are some examples about this on the web, it does not seem to work correctly. I can't figure out the problem.
尽管网络上有一些关于此的示例,但它似乎无法正常工作。我无法弄清楚问题所在。
I have this simple html
我有这个简单的 html
<div id="foo" data-num="0"></ div>
<a href="#" id="changeData">change data value</a>
Every time I click the link "change data value" I want to update the data value of data-num. For example I need it to be 1,2,3,4,... (plus 1 every time I click the link)
每次单击“更改数据值”链接时,我都想更新 data-num 的数据值。例如,我需要它是 1,2,3,4,...(每次单击链接时加 1)
what I have is
我拥有的是
var num = $('#foo').data("num");
console.log(num);
num = num+1;
console.log(num);
$('#foo').attr('data-num', num);
The value changes one time from 0 to 1 every time. I can't make it incremental. Any suggestions what I'm doing wrong?
该值每次从 0 到 1 变化一次。我不能让它增量。任何建议我做错了什么?
采纳答案by Lucas Willems
THE ANSWER BELOW IS THE GOOD ONE
下面的答案是好的
You aren't using the data methodcorrectly. 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)
回答by A. Wolff
Use that instead, if you wish to change the attribute data-num of node element, not of data object:
如果您希望更改节点元素的属性 data-num 而不是 data object ,请改用它:
$('#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...
PS:但是您应该在几乎所有情况下都使用 data() 对象,但不是所有情况...
回答by Lalit Kumar Maurya
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检索或更新这些属性,那么我们可以使用getAttribute
和setAttribute
方法来实现,如下所示:
JavaScript
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
通过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 jsor this documentation for jquery
回答by Brian Ogden
For myself, using Jquery lib 2.1.1 the following did NOT work the way I expected:
就我自己而言,使用 Jquery lib 2.1.1 以下内容没有按我预期的方式工作:
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
我需要更新 DOM,以便稍后可以执行 $('.my-class[data-num="myValue"]') //当前长度为 0
So I had to do
所以我不得不做
$('.my-class').attr('data-num', 'myValue');
To get the DOM to update:
要让 DOM 更新:
<div class="my-class" data-num="myValue"></div>
Whether the attribute exists or not $.attr will overwrite.
属性是否存在 $.attr 将覆盖。
回答by Krist0K
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.
希望这可以帮助。
回答by Sphro
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.
如果使用.data()
它将保存在名为 的局部变量中data_user
,并且在元素检查时不可见,如果使用.attr()
它将公开可见。
Much clearer explanation on this comment
对这个评论更清楚的解释
回答by Giovanni Romio
Had a similar problem, I propose this solution althought is not supported in IE 10 and under.
有一个类似的问题,我提出了这个解决方案,尽管 IE 10 及以下版本不支持。
Given
给定的
<div id='example' data-example-update='1'></div>
The Javascript standard defines a property called dataset to update data-example-update.
Javascript 标准定义了一个名为 dataset 的属性来更新 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
来源:https: //developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
回答by MattOlivos
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.
正如@adeneo 所说,建议不会正确更改您的 Jquery 数据属性的值。但出于某种原因,我没有看到他(或任何其他人)为那些寻求更新数据属性的人发布正确的方法。@Lucas Willems 发布的答案可能是对布赖恩·汤普塞特 - 汤莱恩所面临的问题的答案,但这不是对可能将其他用户带到这里的询问的答案。
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.
容易犯的错误* - 您要更改其值的属性开头必须有“数据-”。
回答by Gash
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.
当我使用 jquery 时,我遇到了同样的 html 数据标签没有更新的问题,但是将执行实际工作的代码从 jquery 更改为 javascript 有效。
Try using this when the button is clicked: (Note that the main code is Javascripts setAttribute()function.)
点击按钮时尝试使用这个:(注意主要代码是Javascripts setAttribute()函数。)
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);
});