繁体   English   中英

JS条件语句不起作用

[英]Js conditional statement not working

在提交时检查weight变量上的非数字输入时,我的if语句似乎不起作用。 为什么是这样?

   submitBtn.onclick = function(){

    var name = document.getElementById('name').value;
    var weight = document.getElementById('weight').value;
    var pound = weight * 2.20462;

    //Check that the value is a number
    if(isNan(weight)){
     alert("Please enter a number);
    }
   }

它在JsFiddle链接中

您的代码中存在多个问题:

  • 您尝试拨打.onclicksubmitBtn ,这是不确定的。
  • 您尝试调用.isNan()这应该是.isNaN()
  • 您无需关闭传递给alert()函数的字符串:
//Define submitBtn
var submitBtn = document.getElementById('submitBtn');
submitBtn.onclick = function(){

    var name = document.getElementById('name').value;
    var weight = document.getElementById('weight').value;
    var pound = weight * 2.20462;

    //Call isNaN()
    if(isNaN(weight)){

        //Close your string
        alert("Please enter a number");
    }
}

的jsfiddle

您可能应该使用isNaN

submitBtn.onclick = function(){

    var name = document.getElementById('name').value;
    var weight = document.getElementById('weight').value;
    var pound = weight * 2.20462;

    //Check that the value is a number
    if(isNaN(weight)){
       alert("Please enter a number");
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM