javascript 表单提交和函数运行后内容立即消失
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21617060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Content disappears immediately after form submitted and function runs
提问by goelv
I'm new to Javascript and HTML.
我是 Javascript 和 HTML 的新手。
I have the following form in HTML:
我在 HTML 中有以下表单:
<div id="form-select">
<form id="date_form" action="" METHOD="POST">
<datalist id="dates">
<option value="February 7">February 7</option>
<option value="February 14">February 14</option>
<option value="February 21">February 21</option>
<option value="February 28">February 28</option>
</datalist>
<input type="text" class="input" name="data" id="date" value="" list="dates" placeholder="pick a date"><br>
<input type="submit" name="submit" onClick="myFunction()"/>
</form>
</div>
Here's the javascript in a file called script.js. The js file is linked in the header as 'script type="text/javascript" src="script.js':
这是名为 script.js 的文件中的 javascript。js 文件在标题中链接为“script type="text/javascript" src="script.js”:
function myFunction(){
var input = document.getElementById("date").value;
if(input==="February 7"){
document.getElementById('w1').innerHTML = "<h2> HEADING </h2>;
}
};
When I fill out the form and hit submit, the javascript correctly executes the function, but the result (i.e. adding HEADING to the html) happens for a couple of milliseconds before disappearing and resetting to the original page before I had hit submit.
当我填写表单并点击提交时,javascript 正确执行该函数,但结果(即向 html 添加 HEADING)发生了几毫秒,然后消失并在我点击提交之前重置到原始页面。
How do I make it so that the insertion of HEADING remains permanent?
如何使 HEADING 的插入保持永久?
回答by RobG
Move the listener to the form's submit handler. Have the function return false to stop submission:
将侦听器移动到表单的提交处理程序。让函数返回 false 以停止提交:
<form id="date_form" onsubmit="return myFunction();" ...>
Take the listener off the button:
将监听器从按钮上取下:
<input type="submit">
Do notgive it a name of submitas that will mask the form's submit method so you can't call it. Submit buttons only need a name if there are two or more on a form and you want to know which one was used to submit the form.
不要给它一个submit的名字,因为这会掩盖表单的提交方法,所以你不能调用它。如果表单上有两个或更多按钮,并且您想知道使用哪个按钮提交表单,则提交按钮只需要一个名称。
There is an error in your code, it's missing a closing double qoute:
您的代码中有错误,缺少结束双引号:
function myFunction(){
var input = document.getElementById("date").value;
if(input==="February 7"){
document.getElementById('w1').innerHTML = "<h2> HEADING </h2>";
}
return false; // to stop submission
};
This may or may not fix you issues, you haven't said what you are actually trying to do.
这可能会也可能不会解决您的问题,您还没有说您实际要做什么。