获取数据属性 jquery vs javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18107181/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:02:07  来源:igfitidea点击:

Get data-attribute jquery vs javascript

javascriptjquerycustom-data-attribute

提问by pedroto

I have a custom data-attribute set by default:

我默认设置了一个自定义数据属性:

data-equipment="0"

data-equipment="0"

If i change it with jquery using .data()

如果我使用.data()用 jquery 更改它

$(this).data("equipment", 10)

$(this).data("equipment", 10)

and then use the getAttribute()

然后使用getAttribute()

this.getAttribute("data-equipment")

this.getAttribute("data-equipment")

i get the old value (0) and not the new one (10). But if i use

我得到旧值 (0) 而不是新值 (10)。但如果我使用

$(this).data("equipment")i get the new value (10).

$(this).data("equipment")我得到新值 (10)。

Is this supposed to work like this or am i missing something?

这应该像这样工作还是我错过了什么?

Thanks!

谢谢!

采纳答案by Esailija

.data()doesn't operate on data attributes but in internal jQuery cache. Initially if no cache record is found, the data is read from a corresponding data-attribute if one exists, but that is the end of their co-operation.

.data()不对数据属性进行操作,而是在内部 jQuery 缓存中操作。最初,如果没有找到缓存记录,则从相应data-属性(如果存在)读取数据,但这是它们合作的结束。

If it operated on attributes, it would be useless for its purpose because attribute values must be strings.

如果它对属性进行操作,那么它的用途将毫无用处,因为属性值必须是字符串。