最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - HTML data and a string that looks like a number - Stack Overflow

programmeradmin6浏览0评论

For this html

<div data-a="0123"></div>

this js:

console.log($('div').data('a'));

returns 123. Is there any way without adding extra-chars and cutting it to get a string 0123?

Jsfiddle: /

For this html

<div data-a="0123"></div>

this js:

console.log($('div').data('a'));

returns 123. Is there any way without adding extra-chars and cutting it to get a string 0123?

Jsfiddle: http://jsfiddle/PXw2J/

Share Improve this question asked Oct 27, 2011 at 6:59 zerkmszerkms 255k73 gold badges447 silver badges547 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

From the jQuery doco on .data():

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.

So you need to say:

console.log($('div').attr('data-a'));

(Note that you specify the full attribute name, including the 'data-' prefix.)

You can bypass data() and grab the attribute directly:

console.log($('div').attr('data-a'));

Demo

Yep, use:

console.log($('div').attr('data-a'));
发布评论

评论列表(0)

  1. 暂无评论