如果函数中的语句不起作用

时间:2017-04-06 05:15:47

标签: javascript function if-statement conditional-statements getelementbyid

由于某些未知原因,checkID函数中的if语句已停止工作,并且只显示' OK'无论输入什么输入。我不确定自己做错了什么,但有人可以查看我的代码。目前,代码似乎只是在函数中运行最后一个if语句,而只有最后一条消息是" Ok"。

这是我的HTML:



function begin() {
  var Name = document.forms["Cars"]["Name"].value;
  var NameID = document.forms["Cars"]["NameID"].value;
  var IDName = "";
  var PersonID = "";

  var checklength = Name.length;
  CheckName();
  console.log(checklength, checklength < 100)
  var checkIDlength = NameID.length;
  checkID();
  console.log(checkIDlength, checkIDlength < 100)
  return false;


  function CheckName() {
    if (checklength > 0 && checklength < 21) {
      IDName = "Ok"
    } else {
      IDName = "Invalid Name Length";
    }

    document.getElementById('IDName').innerHTML = IDName;
    return false;
  }

  function checkID() {
    if (checkIDlength != 6) {
      PersonID = "Invalid ID Length"
    }
    document.getElementById('PersonID').innerHTML = PersonID

    if (NameID.indexOf('BR') === 0) {} else {
      PersonID = "Invalid ID Type"
      document.getElementById('PersonID').innerHTML = PersonID

    }
    if (isNaN(NameID.Length != 2)) {
      PersonID = "The Last 2 Digits must be numeric";
    } else {
      PersonID = "OK"
      document.getElementById('PersonID').innerHTML = PersonID
    }
  }
}
&#13;
<!DOCTYPE html>
<html>

<body>
  <form name="Cars">
    <h1>Car Sales</h1>
    <p>Enter Name</p>
    <input type="text" style="text-transform: uppercase" name="Name"><br>
    <p id="IDName"></p>
    <p>Enter ID</p>
    <input type="text" name="NameID"><br>
    <p id="PersonID"></p>
    <br>
    <button onclick="return begin()">Calculate</button>
  </form>
</body>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

看起来我已经通过在IDCheck功能的if语句中添加一些返回false来使用&#34; BR1231&#34;作为我的测试用例,我不确定这是否100%有效,但这是我的代码:

    function begin() {
  var Name = document.forms["Cars"]["Name"].value;
  var NameID = document.forms["Cars"]["NameID"].value;
  var IDName = "";
  var PersonID = "";

var checklength = Name.length;
CheckName();
console.log(checklength, checklength < 100)
var checkIDlength = NameID.length;
checkID();
console.log(checkIDlength, checkIDlength < 100)
return false;


function CheckName(){
  if (checklength >0 && checklength <21)
  {
IDName = "Ok"
  }
  else{
    IDName = "Invalid Name Length";
  }

  document.getElementById('IDName').innerHTML = IDName;
  return false;
}


function checkID(){
  if (checkIDlength !=6)
  {
    PersonID = "Invalid ID Length"

 document.getElementById('PersonID').innerHTML = PersonID
 return false;
}

  if (NameID.indexOf('BR') === 0) {
  }
  else {
    PersonID = "Invalid ID Type"
   document.getElementById('PersonID').innerHTML = PersonID
     return false;

}
   if (isNaN(NameID.Length !=2))
  {
   PersonID = "The Last 2 Digits must be numeric";
     return false;

 }
 else{
    PersonID = "OK"
    document.getElementById('PersonID').innerHTML = PersonID

 }

}
}