2017-04-06 465 views
0

我目前正在为我的uni课程学习JavaScript,因为某些原因我的函数没有被调用。我想了解为什么这不起作用。JavaScript:表单onSubmit不能调用函数

简要说明

有两种形式,一是有一个提交按钮,与onSubmit场调用document.write()(这工作),然后调用我自己的函数submit()。如果我将submit()更改为document.write(),那么我收到两个输出,所以不应该读取为什么submit未被调用?

第二种形式在其中有一个单独的文本框,我希望在按下按钮时使其消失,但是我主要想知道为什么不调用submit

<html charset="utf-8"> 
<head> 
    <title>Game</title> 
</head> 
<body> 
    <form method="get" name="form1" action="game.php" onSubmit="document.write('Hello');submit();"> 
     <input type="submit" value="submit" name="button" /> 
    </form> 

    <form id="form2" name="form2"> 
     <input name="letter" type="text" /> 
    </form> 
    <script> 
     function submit() { 
      alert("HELLO"); 
      document.getElementById('form2').visibility='hidden'; 
      document.write("Hello"); 
     } 
    </script> 
</body> 

我试图插入脚本的头,上面的函数,该函数下方,但似乎没有任何工作。

希望有人能帮助,谢谢

回答

5

提交是保留关键字。更改为任何其他名称,它应该工作。请找相同

https://jsfiddle.net/pc9rL2ey/

 function submita() { 
      alert("HELLO"); 
      document.getElementById('form2').visibility='hidden'; 
      document.write("Hello"); 
     } 


<form method="get" name="form1" action="game.php" onSubmit="submita();document.write('Hello');"> 
+0

参见[这里]中的jsfiddle(https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit)为(简洁?)文件。 – SinDeus