jQuery data() returns undefined, attr() returns integer

故事扮演 提交于 2019-11-26 18:15:12

问题


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.

-- SEE DEMO --

I'm using jQuery version 1.7.2 (data was added with version 1.4 I believe)

Why is this? Should I be using data() at all if its not returning the right values?


回答1:


OK. I found the problem by interpreting jQuery docs.

When you write:

$embellishment.data("embellishmentId");

it is handled by jQuery as compound attribute:

<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");


来源:https://stackoverflow.com/questions/10992984/jquery-data-returns-undefined-attr-returns-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!