本文介绍了parseInt总是返回NaN?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

长话短说,我试图验证一个手机领域。我添加
isNaN parseInt 用于检查在现场,但是说

long story short, i was trying to validate a phone field. ive addedthe isNaN and parseInt for checking the " " in the field but that said

以下从未验证为真......我错过了什么?

This below never validates to true..what am i missing?

if(isNaN(parseInt(phone))){
        error.text("Sorry but this phone field requires numbers only");
        return false;
    } else {
    return true;

    }

它总是失败......即使是我在现场输入一个号码并提交。
i总是得到错误mssg。

it always fails...it never reads true even when i enter a number in the field and submit.i always get the error mssg.

编辑: 我正在测试表单中的输入值, 电话是该字段的名称。

推荐答案

各种方法来强迫JS字符串与数字及其后果:

Various ways to coerse JS strings to numbers, and their consequences:

我个人使用 * 1 因为它很短,但仍然很突出(与一元+不同),并且或者给我用户输入或完全失败的内容。我只使用 parseInt()当我知道时,最后会有非数字内容忽略,或者我需要解析一个非基数为10的字符串。

I personally use *1 as it is short to type, but still stands out (unlike the unary +), and either gives me what the user typed or fails completely. I only use parseInt() when I know that there will be non-numeric content at the end to ignore, or when I need to parse a non-base-10 string.

编辑:根据您的评论,如果使用 phone.val()修复它然后

Edit: Based on your comment, if using phone.val() fixed it then


  1. 您使用的是jQuery(您从未提及过,应该有),并且

  2. 你实际拥有一个jQuery对象,包装一个或多个DOM元素(可能只有一个)。

每当你执行 var foo = $('...'); 然后 foo 变量引用一个jQuery对象一个或多个元素。您可以通过 var fooEl = foo [0]; var fooEl = foo.get(0); ...但即便如此,你仍然有一个DOM元素而不是它的特定属性。

Whenever you do var foo = $('…'); then the foo variable references a jQuery object of one or more elements. You can get the first actual DOM element from this via var fooEl = foo[0]; or var fooEl = foo.get(0);…but even then you still have a DOM element and not a particular property of that.

对于表单输入,你需要从DOM元素中获取 .value ,这就是jQuery .val()方法的作用。

For form inputs, you need to get the .value from the DOM element, which is what the jQuery .val() method does.

这篇关于parseInt总是返回NaN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:14
查看更多