防止将包含E和数字的字符串转换为数字 [英] Prevent converting string containing an E and numbers to number

查看:161
本文介绍了防止将包含E和数字的字符串转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有这种'奇怪'的情况,当在jquery点击功能中检索时,存储在数据属性(ex data-prodcode)中的某些产品代码(例如11E6)将转换为11000000。这样的事情:

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?

推荐答案

来自文档


每次尝试将字符串转换为JavaScript值
(包括布尔值,数字,对象,数组,和null)否则
它保留为字符串。要将值的属性检索为字符串
而不尝试转换它,请使用attr()方法。

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.

您可以使用 attr 以避免自动解析:

You may use attr in order to avoid automatic parsing :

var code = $(this).attr('data-prodcode');

更确切地说:这不应该发生。事实上,它不会发生在最新版本中。这是当前jQuery的代码(最有趣的部分是注释):

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 comment) :

    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 ) {}

它适用于jQuery 1.8和1.9:它如果后向转换不生成相同的字符串,则不会将字符串转换为数字。但它在jQuery 1.7中不起作用。

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.

这篇关于防止将包含E和数字的字符串转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆