innerHTML返回带有文本的NaN [英] innerHTML return NaN with text

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

问题描述

我遇到了问题, 我尝试用innerHTML返回一个值,但得到了NaN. 我知道我的变量不是数字,而是他为什么一直告诉我?

I got a problem, I try to return a value with innerHTML but I got a NaN. I know my variable is not a number but why he keep telling me that ?

function checkWord(id, nameOutput){
    var pattern = new RegExp("\\b(hello|world)\\b", "i");
    var fieldValue = document.getElementById(id).value;
    var result = fieldValue.search(pattern);
    if (result != -1){
        document.getElementById(nameOutput).style.color = "green";
        document.getElementById(nameOutput).innerHTML = +fieldValue+ " is correct";
    }
    else{
        document.getElementById(nameOutput).style.color = "red";
        document.getElementById(nameOutput).innerHTML = +fieldValue+ " is incorrect";
    }
    if(fieldValue == null || fieldValue == ""){
        document.getElementById(nameOutput).style.color = "orange";
        document.getElementById(nameOutput).innerHTML = "Empty field";
    }     
} 

我总是 NaN不正确 NaN是正确为什么我无法获得值print?

I got always NaN is incorrect or NaN is correct why i can't get the value print ?

如果我这样写:

document.getElementById(nameOutput).innerHTML ="" +fieldValue+ " is correct";
document.getElementById(nameOutput).innerHTML ="" +fieldValue+ " is incorrect";

一切正常!但是为什么我需要在innerHTML

Everything works well !! but why i need to write this "" in the innerHTML

我做错了吗?

推荐答案

更改

document.getElementById(nameOutput).innerHTML = +fieldValue+ " is correct";

document.getElementById(nameOutput).innerHTML = fieldValue + " is correct";

因为= +fieldValue否则缺少要添加/连接到fieldValue的内容.因此,将强制转换为导致未定义数字或NaN的数字.

because = +fieldValue is otherwise missing something to add/concatenate to fieldValue. So, instead a cast is made to a number which results in an undefined number, or NaN.

尝试时

document.getElementById(nameOutput).innerHTML ="" +fieldValue+ " is correct"; 

您提供了一些要连接到fieldValue的东西,即一个空字符串,因此没有在fieldValue上执行任何数字转换.

you supplied something to concatenate to fieldValue, namely an empty string, so no number conversion was performed on fieldValue.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆