[英]jQuery data-attribute is cutting of leading zero
I'm attempting to grab a data-* with jQuery. 我试图用jQuery获取数据 - *。 My problem is that jQuery reads my string of numbers as a number and as such drops the leading zero.
我的问题是jQuery将我的数字字符串作为数字读取,因此会丢弃前导零。
HTML HTML
<tr data-string-number="0123456789">... (website layout, jk) ...</tr>
jQuery 1.7.2 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. data-string-number
总是一个数字,可能有也可能没有前导零。 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 . .data()
方法通过设计进行数据转换。 The .attr()
method simply returns the attribute as is (as a string). .attr()
方法只是按原样返回属性(作为字符串)。 Note that when using .attr()
you need to supply the full name of the attribute including the "data-"
prefix. 请注意,使用
.attr()
您需要提供属性的全名,包括"data-"
前缀。
I know this is old but I have 2 alternative to using the .attr() for accessing the data as a string. 我知道这是旧的,但我有两种方法可以使用.attr()以字符串形式访问数据。
<!-- 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. 现在,您可以使用jQuery .data()方法访问它们。
See this fiddle to illustrate http://jsfiddle.net/KUrJ2/ . 看到这个小提琴来说明http://jsfiddle.net/KUrJ2/ 。
Get the attribute with the standard attr()
accessor. 使用标准
attr()
访问器获取属性。
jQuery tries to guess the type and convert it when using data()
on data-*
attributes. jQuery尝试猜测类型并在
data-*
属性上使用data()
时转换它。 As we know leading 0
's are insignificant in a Number
but not a String
. 我们知道前导
0
在Number
是无关紧要的,但不是String
。
use the jquery attr() 使用jquery attr()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.