如何从 HTML 获取输入以链接到 MyChecker 函数?它不起作用

How to I get the input from the HTML to link to the MyChecker function? It doesn't work

本文关键字:MyChecker 函数 不起作用 链接 HTML 获取 输入      更新时间:2023-09-26

这是我使用的代码。它从用户那里获取名字和姓氏,然后在MyChecker函数中使用它们,在其中匹配用于创建不同警报的名称。我无法让 MyChecker 函数链接到用户输入的值?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Question 1</title>
</head>
<body>
    <p>What's your name?</p>
    <form action="action.php"> //This form gets the input from the user
        First Name
        <br><input type="text" name="FirstName" value="" id="txt1"><br>
        Second Name
        <br><input type="text" name="SecondName" value="" id="txt2"><br>
        <button onclick="myFunction()">Submit</button>
    </form>
<script type="text/javascript">
function myFunction() { //This function gets the values inputted by the user
  document.getElementById('txt1').value);
  document.getElementById('txt2').value);
}
var x= FirstName.localeCompare("Donald");
var y= SecondName.localeCompare("Trump");
MyChecker();
function MyChecker()
{
  if(x==0&&y==0)
  {
    alert("I love the poorly educated");
  }
  var a= FirstName.localeCompare("Edward");
  var b= SecondName.localeCompare("Snowden");
  if(a==0 && b==0)
  {
    var ask=prompt("Would you mind collecting your cake from our office in Pennsylvania?","Choose between yes or no");
    var cmp=ask.localeCompare("yes");
    if(cmp==0)
    {
      alert("We'll even reimburse your plane tickets!");
    }
    else
    {
      alert("Perhaps next time...");
    }
  }
  if(a!=0 && b !=0 && x !=0 && y!=0)
  {
    alert("Carry on...");
  } 
}
</script>
</body>
</html>

我修饰了你的缩进,希望它有助于暴露问题。 当您提交表格时,您将调用myFunction,为了清楚起见,我将其复制到此处:

function myFunction() { //This function gets the values inputted by the user
  document.getElementById('txt1').value);
  document.getElementById('txt2').value);
}

。仅此而已。 这些值甚至不会保存。

您可能的意思是myFunction调用MyChecker,以便每次提交表单时都会执行您的逻辑。

您还可以考虑让MyCheckerFirstNameSecondName作为参数,因为myFunction已经从表单中读取值。