【发布时间】:2012-01-20 05:53:53
【问题描述】:
我刚刚写了一个小程序,它接受用户的输入并显示阶乘表。代码如下:
<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
【问题讨论】:
-
jsfiddle.net/d2DqP/7 我用 chrome 试过了,效果很好。
-
对我来说它显示了表格,然后在你的 jsfiddle 中再次返回到表格:(..我希望它停在桌子上
-
是表单提交事件导致的重载吗?
-
但是表单中没有提交事件
-
@unussunu 有一个输入类型按钮,在某些浏览器上具有默认提交操作。
标签: javascript reload onchange