javascript:如何阻止页面重装? [英] javascript: how to stop the page from reloading?
问题描述
我刚写了一个小程序,它从用户那里获取输入并显示了阶乘表。以下是代码:
I just wrote a small program which takes the input from user and shows the factorial table. Here is the code:
<h1>Table of factorials</h1>
<h3>Enter the number:<h3>
<form name="form1">
<input type="text" name="num" onchange="display(parseInt(document.form1.num.value))"/>
<input type="button" />
</form>
<script>
function factorial(n){
if(n<=1) return n;
else return n*factorial(n-1);
}
function display(x){
document.write("<table>");
document.write("<tr><th>n</th><th>n!</th></tr>");
for(var i =1;i<=x;i++){
document.write("<tr><td>"+i+"</td><td>"+factorial(i)+"</td></tr>");
}
document.write("</table>");
document.write("Generated at"+ new Date());
}
</script>
但问题是表格显示后表格会立即重新加载。
但是如果我使用按钮来触发函数 onclick =display(parseInt(document.form1.num.value))
它就可以了。
如何解决此问题?
编辑:刚刚注意到它在firefox中运行正常。问题在于chrome,opera和safari
But the problem is the form reloads again immediately after showing the table.
But if i use the button to trigger the function by onclick="display(parseInt(document.form1.num.value))"
it does fine.
How to fix this?
Just noticed that it works fine in firefox too. The problem is with chrome, opera and safari
推荐答案
阻止输入按钮的默认操作。您可以通过JQuery的 preventDefault()
函数来执行此操作。或者只需< form onsubmit =return false;> ...< / form>
prevent the default action of the input button. You can do this by JQuery's preventDefault()
function .Or just <form onsubmit="return false;"> ... </form>
这篇关于javascript:如何阻止页面重装?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!