简体   繁体   中英

jQuery data-attribute is cutting of leading zero

I'm attempting to grab a data-* with jQuery. My problem is that jQuery reads my string of numbers as a number and as such drops the leading zero.

HTML

<tr data-string-number="0123456789">... (website layout, jk) ...</tr>

jQuery 1.7.2

var string_number = $('#selector').data('string-number');
// string_number == 123456789
// string_number != '0123456789'

Seems simple enough however this always drops the leading zero.

data-string-number is always going to be a number and may or may not have a leading zero. Currently it has a standard length but I can't say at this point if that will stay true.

Current only thought is to prefix it with a non-numeric and remove it straight away. This feels hacky and makes me sad.

Any thought appreciated.

Thanks.

Use this:

$('#selector').attr('data-string-number')

The .data() method does data conversion by design . The .attr() method simply returns the attribute as is (as a string). Note that when using .attr() you need to supply the full name of the attribute including the "data-" prefix.

I know this is old but I have 2 alternative to using the .attr() for accessing the data as a string.

<!-- Force a String by breaking the parser Remove Quotes later
or Use Object Below -->
<li data-tmp='"0123456789"'>Data as a String: </li>
<li data-tmp='{"num":123456789,"str":"0123456789"}'>Data as a Object: </li>

Now you can access them with the jQuery .data() method.

See this fiddle to illustrate http://jsfiddle.net/KUrJ2/ .

Get the attribute with the standard attr() accessor.

jQuery tries to guess the type and convert it when using data() on data-* attributes. As we know leading 0 's are insignificant in a Number but not a String .

use the jquery attr()

http://jsfiddle.net/duerq/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM