val() 如何返回数字?

2022-01-17 00:00:00 string numbers jquery javascript

valdocs中写了这样的描述:

.val() 返回:字符串、数字、数组

.val() Returns: String, Number, Array

我试图获取一个 Number,但它似乎只返回 string,是不是我做错了什么?

I tried to get a Number, but it seems to return string only, Is there something that I'm doing wrong?

$('#gdoron').val('1');

alert($('#gdoron').val() === '1'); // true 
alert(typeof $('#gdoron').val());  // string.

$('#gdoron').val(1);

alert($('#gdoron').val() === 1);  // false
alert(typeof $('#gdoron').val()); // string (not "number"!)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="gdoron" />

我的问题是:val() 如何按照文档所述返回数字? 问题不在于如何解析字符串.

My question is: how can val() return number as the docs says? The question is not about how can I parse the string.

推荐答案

一些 HTML5 元素,例如进展;

Some HTML5 elements e.g. progress;

console.log(typeof $("#prog").val()); // number 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<progress value="50" max="100" id="prog"></progress>

相关文章