Prevent converting string containing an E and numbers to number

会有一股神秘感。 提交于 2019-12-06 03:00:07

问题


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?


回答1:


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

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.



来源:https://stackoverflow.com/questions/14940778/prevent-converting-string-containing-an-e-and-numbers-to-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!