javascript 为什么这个函数返回Nan错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11049504/
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
Why this function return Nan error?
提问by xRobot
When I click "+ 1", then in the "0" appears "NaN". Why ?
当我单击“+ 1”时,则在“0”中出现“NaN”。为什么 ?
HTML:
HTML:
<table>
<tr><td id="run">0</td></tr>
</table>
<a href="#" onclick="plus();">+ 1 </a>
JS:
JS:
function plus(){
document.getElementById("run").innerHTML = ( document.getElementById("run").value + 1 );
}
回答by VisioN
It happens because value
property can be applied only to input
or select
elements.
发生这种情况是因为value
属性只能应用于input
或select
元素。
Pay attention that you need to convert your string value to numeric, otherwise you will get string concatenation. It can be done with parseInt
or parseFloat
functions.
注意你需要将你的字符串值转换为数字,否则你会得到字符串连接。它可以用parseInt
或parseFloat
函数来完成。
var val = parseInt(document.getElementById("run").innerHTML, 10);
document.getElementById("run").innerHTML = ( val + 1 );
回答by Ja?ck
That's because:
那是因为:
document.getElementById("run").value
will be undefined
and undefined + 1 == NaN
.
将是undefined
和undefined + 1 == NaN
。
Input boxes have a value
property, but nodes like <td />
have .innerHTML()
or .innerText()
.
输入框有一个value
属性,但是像<td />
has.innerHTML()
或 之类的节点.innerText()
。
Also, note that '0' + 1 == '01'
, so you have to do some casting as well:
另外,请注意'0' + 1 == '01'
,因此您还必须进行一些转换:
parseInt(document.getElementById('run').innerHTML, 10) + 1;
The additional radix - 10 - is necessary to convert strings that may be interpreted as octal numbers :)
附加基数 - 10 - 是转换可能被解释为八进制数的字符串所必需的:)
回答by Wouter J
Because attribute values are always strings and string + 1 is a NaN in JavaScript.
因为属性值始终是字符串,而 string + 1 在 JavaScript 中是 NaN。
To solve this, use string.toFloat()
:
要解决此问题,请使用string.toFloat()
:
function plus(){
document.getElementById("run").innerHTML = ( document.getElementById("run").value.toFloat() + 1 );
}
Or use parseInt()
:
或使用parseInt()
:
function plus(){
document.getElementById("run").innerHTML = ( parseInt(document.getElementById("run").value) + 1 );
}
Or use the ~~()
function as a trick, but this will result in a not readable source.
或者将该~~()
函数用作技巧,但这会导致源代码不可读。
回答by raina77ow
I guess this question still deserve a better answer, but I may be wrong. )
我想这个问题仍然值得更好的答案,但我可能错了。)
Let's check what happens in your plus
function. First, you get an element by its id, with
让我们检查一下您的plus
函数中发生了什么。首先,你通过它的 id 得到一个元素,用
var targetElement = document.getElementById('run');
It's actually a reference to the object of DOMElementtype. Which is quite easy to see by checking its nodeType property.
它实际上是对DOMElement类型的对象的引用。通过检查它的 nodeType 属性很容易看到。
if (targetElement.nodeType === 1) { alert("It's an element!"); }
DOM Elements have plenty of nice properties, but their nodeValue
is always equal to null. So if you want to work with its text content, you can either look for the child textNodes - or just use innerHTML
property. It's a string, yes, but Javascript will manage to convert it to a normal number if it's numeric (and 0 is numeric, from what I remember :).
DOM元素有很多漂亮的性质,但他们的nodeValue
是总是等于零。因此,如果您想处理其文本内容,您可以查找子 textNodes - 或仅使用innerHTML
属性。它是一个字符串,是的,但是如果它是数字,Javascript 会设法将它转换为普通数字(我记得 0 是数字:)。
So your plus
function can be actually written just like this (the proof):
所以你的plus
函数实际上可以像这样写(证明):
document.getElementById('run').innerHTML++;
回答by ZER0
Because value
is a property of HTMLInputElementand the TD
element is not an HTMLInputElement
but a HTMLTableCellElement
, so doesn't have that property and:
由于value
是一个属性HTMLInputElement和TD
元素不是一个HTMLInputElement
而是一个HTMLTableCellElement
,因此不具有财产:
undefined + 1; // NaN - Not a Number
You can basically use the same innerHTML
property you used to set the content also to get it:
您基本上innerHTML
可以使用与设置内容相同的属性来获取它:
function plus() {
// no need to execute `getElementById` twice
var td = document.getElementById("run");
td.innerHTML = +td.innerHTML + 1;
}
To convert the value in Number I used the unary plus operator. You could also check if it's NaN
before use it, something like:
为了转换 Number 中的值,我使用了一元加运算符。您还可以NaN
在使用之前检查它是否存在,例如:
function plus() {
var td = document.getElementById("run");
var value = +td.innerHTML || 0;
td.innerHTML = value + 1;
}
In that case if it's NaN
(or 0, but in that case it's an identity) will set to 0, and the count will start from 1
without give any error.
在这种情况下,如果它是NaN
(或 0,但在这种情况下它是一个身份)将设置为 0,并且计数将从1
不给出任何错误开始。
Additionally, I would say that it could be better use the textContentproperty where supported, but then the code will be a bit more complex to handle all browser's (e.g. in some IE versions you need to use innerText
instead), and innerHTML
could be good in most of the cases.
此外,我会说在支持的地方使用textContent属性可能会更好,但是处理所有浏览器的代码会稍微复杂一些(例如,在某些 IE 版本中您需要使用innerText
),并且innerHTML
在大多数情况下可能会很好的情况。
回答by ZER0
Try this
试试这个
function plus(){
document.getElementById("run").innerHTML = parseInt( document.getElementById("run").value) + 1;
}