admin管理员组文章数量:1415484
We have this 'strange' situation where some product codes, for example 11E6, which are stored in data attributes (ex data-prodcode) are getting converted to 11000000, when retrieved inside jquery click function. Something like this:
<a data-prodcode="11E6">click</a>
var code = $(this).data('prodcode');
console.log(code); --> 11000000
Any advice on how to avoid this behavior or what may cause it?
We have this 'strange' situation where some product codes, for example 11E6, which are stored in data attributes (ex data-prodcode) are getting converted to 11000000, when retrieved inside jquery click function. Something like this:
<a data-prodcode="11E6">click</a>
var code = $(this).data('prodcode');
console.log(code); --> 11000000
Any advice on how to avoid this behavior or what may cause it?
Share Improve this question edited Feb 18, 2013 at 16:32 Denys Séguret 383k90 gold badges811 silver badges776 bronze badges asked Feb 18, 2013 at 16:24 user1398498user1398498 4291 gold badge5 silver badges14 bronze badges 1-
3
That's because
.data
attempts to auto-convert values into numbers or Booleans when possible, and the string11E6
looks like a number in scientific notation to a puter. – Blazemonger Commented Feb 18, 2013 at 16:25
1 Answer
Reset to default 7From the documentation :
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.
You may use attr
in order to avoid automatic parsing :
var code = $(this).attr('data-prodcode');
To be more precise : this shouldn't happen. And in fact it doesn't happen in last versions. Here's the code of current's jQuery (the most interesting part is the ment) :
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
And it works in jQuery 1.8 and 1.9 : it doesn't convert the string to a number if a back conversion doesn't produce the same string. But it didn't work in jQuery 1.7.
本文标签: javascriptPrevent converting string containing an E and numbers to numberStack Overflow
版权声明:本文标题:javascript - Prevent converting string containing an E and numbers to number - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745232468a2648886.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论