Javascript jQuery data() 返回未定义,attr() 返回整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10992984/
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
jQuery data() returns undefined, attr() returns integer
提问by Curt
I have the following code:
我有以下代码:
alert($embellishment.data("embellishmentId"));
alert($embellishment.attr("data-embellishmentId"));
The first alert returns undefined
, whereas the second alert returns an integer, 3
.
第一个警报返回undefined
,而第二个警报返回整数3
。
I'm using jQuery version 1.7.2 (data
was added with version 1.4 I believe)
我正在使用 jQuery 1.7.2 版(data
我相信是 1.4 版添加的)
Why is this? Should I be using data()
at all if its not returning the right values?
为什么是这样?data()
如果它没有返回正确的值,我应该使用它吗?
回答by VisioN
OK. I found the problem by interpreting jQuery docs.
好的。我通过解释jQuery 文档发现了这个问题。
When you write:
当你写:
$embellishment.data("embellishmentId");
it is handled by jQuery as compound attribute:
它由 jQuery 作为复合属性处理:
<div data-embellishment-id="3"></div>
So, to solve the problem you can use lower case in the data key otherwise it just addresses the different attribute.
因此,要解决该问题,您可以在数据键中使用小写字母,否则它只会解决不同的属性。
<!-- HTML -->
<div data-embellishmentid="3"></div>
// JavaScript
$embellishment.data("embellishmentid");