开发者

Is using .data() to retrieve the value of data-* attributes a good idea?

In my project I am currently using some custom data-* attributes in my HTML to convey some extra data that will be used by jQuery. I found the .data() method and noticed that if I have a data-* attribute data-my-attribute that I can retrieve its value in jQuery by selecting the element with the attribute and calling .data("my-attribute").

I assumed that this was the way it is supposed to be used (did not look into the documentation) and used it through out my jQuery code. However, now I noticed that when I put for example a string "000005643" in the HTML data-* attribute, .data("my-attribute") return 5643 while .attr("data-my-attribute") return "000005643". Where the latter is what I wanted. This led me to look up the documentation and actually found out that there is more to .data() than I thought. Also, I never saw any text or example that indicates you should use .data() to retrieve values of data-* attributes. This worries me that I am doing something fundamentally wrong.

So should I cease and desist with using .data() in this manner or not? If not, could you开发者_运维百科 link me to some documentation about the .data() function that explains this use.


The data() method returning HTML5 data-* attributes was introduced in 1.4.3.

As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object.

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string. To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method.

Source.

It appears jQuery is certain you want a number, so it is returning a Number for you, not the String.

If you want it as a string, use attr().


I'm actually working on porting this functionality to Zepto. Yeah, it's not really something wrong with the data- HTML spec but it's just jQuery's implementation of it. It's trying to work around the fact that data- doesn't handle non-strings very well and then it tries to be fancy and pull out values like null, ints, and floats for you. I suppose a workaround is putting a string character in front of your value and substr'ing it off when you retrieve it. Either that or use attr('data-') - though going back and forth between .data and .attr could lead to different results as you've noticed. Stick with one or the other.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜