在下面的代码中,我试图调用 valueAsNumber
但我只得到一个 NaN 返回.当我使用 parseInt
时,我得到了我期望的结果.这是为什么呢?
In the code below, I am trying to call valueAsNumber
but I just get a NaN returned. When I use parseInt
I get the result I expect. Why Is this?
<html>
<head>
<title>JavaScript: Demo 1</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<div id="numbers">
<div id="inputs">
<form name="inputForm">
<div class="prompt">Number 1: <input name="number1" type="text"></div>
<div class="prompt">Number 2: <input name="number2" type="text"></div>
</form>
</div>
<div id="result">
<div class="prompt">RESULT: <span id="operation_result"> </span></div>
</div>
</div>
<div id="operations">
<p><a id="add_link" href="#" onClick="add(this)">ADD</a></p>
</div>
<script type="text/javascript">
function add(linkElement){
// var value1 = parseInt(document.inputForm.number1.value);
// var value2 = parseInt(document.inputForm.number2.value);
var value1 = document.inputForm.number1.valueAsNumber;
var value2 = document.inputForm.number2.valueAsNumber;
var result = value1 + value1;
document.getElementById('operation_result').innerHTML = result;
}
</script>
</body>
</html>
考虑到属性名称,您的期望是合理的,但阅读实际 规格/文档:
Your expectations are reasonable considering the property name, but reading actual specs/documentation:
valueAsNumber IDL 属性表示元素的值,解释为数字.
The valueAsNumber IDL attribute represents the value of the element, interpreted as a number.
获取时,如果 valueAsNumber 属性不适用,如定义对于输入元素的类型属性的当前状态,然后返回一个非数字 (NaN) 值.
On getting, if the valueAsNumber attribute does not apply, as defined for the input element's type attribute's current state, then return a Not-a-Number (NaN) value.
这是一个表格,它列出了适用于 valueAsNumber
的 type
.它们是:
Here's a table that list's type
s that apply to valueAsNumber
. These are:
datetime
)(请注意,此 type=""
现在在 HTML LS 中已过时)日期
)月
)周
)时间
)datetime-local
)编号
)范围
)datetime
) (Note this type=""
is now obsolete in HTML LS)date
)month
)week
)time
)datetime-local
)number
)range
)观察到 type="text"
明显不在上述列表中,因此 textInput.valueAsNumber
将始终返回 NaN
即使 isNaN( parseInt( textInput.value, 10 ) ) === false
.
Observe that type="text"
is conspicuously absent from the above list, therefore textInput.valueAsNumber
will always return NaN
even when isNaN( parseInt( textInput.value, 10 ) ) === false
.
这篇关于为什么“valueAsNumber"返回 NaN 作为值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!