使用 jQuery 解析 Int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9775375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:17:17  来源:igfitidea点击:

parseInt with jQuery

jquery

提问by Floppy88

Can someone help me figuring out why the following jQuery code doesn't work? I want to return a integer from an user input.

有人能帮我弄清楚为什么下面的 jQuery 代码不起作用吗?我想从用户输入中返回一个整数。

var test = parseInt($("#testid"));

Thank you & bye!

谢谢你,再见!

回答by jondavidjohn

var test = parseInt($("#testid").val(), 10);

You have to tell it you want the valueof the input you are targeting.

你必须告诉它你想要value你所针对的输入。

And also, always provide the second argument (radix) to parseInt. It tries to be too clever and autodetect it if not provided and can lead to unexpected results.

而且,始终为 提供第二个参数(基数)parseInt。它试图过于聪明并在未提供时自动检测它,并可能导致意外结果。

Providing 10assumes you are wanting a base 10 number.

提供10假设您想要一个基数为 10 的数字。

回答by T.J. Crowder

Two issues:

两个问题:

  1. You're passing the jQuery wrapper of the element into parseInt, which isn't what you want, as parseIntwill call toStringon it and get back "[object Object]". You need to use valor textor something (depending on what the element is) to get the string you want.

  2. You're not telling parseIntwhat radix (number base) it should use, which puts you at risk of odd input giving you odd results when parseIntguesses which radix to use.

  1. 您正在将元素的 jQuery 包装器传递给parseInt,这不是您想要的,因为parseInt会调用toString它并返回"[object Object]"。您需要使用valortext或其他东西(取决于元素是什么)来获取您想要的字符串。

  2. 你没有告诉parseInt它应该使用什么基数(数字基数),这会让你在parseInt猜测使用哪个基数时有奇数输入给你奇怪结果的风险。

Fix if the element is a form field:

修复元素是否为表单域:

//                               vvvvv-- use val to get the value
var test = parseInt($("#testid").val(), 10);
//                                    ^^^^-- tell parseInt to use decimal (base 10)

Fix if the element is something else and you want to use the text within it:

如果元素是其他元素并且您想使用其中的文本,请修复:

//                               vvvvvv-- use text to get the text
var test = parseInt($("#testid").text(), 10);
//                                     ^^^^-- tell parseInt to use decimal (base 10)

回答by Prasanna

var test = parseInt($("#testid").val());