문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top