Js 条件语句不起作用

Js conditional statement not working

本文关键字:不起作用 语句 条件 Js      更新时间:2023-09-26

我的 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 链接中

代码中存在多个问题:

  • 您尝试在未定义的 submitBtn 上调用 .onclick
  • 您尝试调用应该.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");
    }
}