我剛剛寫了一個小程序,它接受用戶的輸入並顯示階乘表。這裏是代碼:javascript:如何阻止重新加載頁面?
<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中也能正常工作。問題是與鍍鉻,Opera和Safari
http://jsfiddle.net/d2DqP/7/我試過在鉻,它只是工作正常。 – xdazz
對我來說,它顯示了表格,然後再次返回到你的jsfiddle中的窗體:(我想讓它停在桌子上 – tarashish
是否由表單提交事件造成重新加載? –