【问题标题】:javascript: how to stop the page from reloading?javascript:如何阻止页面重新加载?
【发布时间】: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


【解决方案1】:

使用&lt;form onsubmit="return false;"&gt; ... &lt;/form&gt;

【讨论】:

    【解决方案2】:

    防止输入按钮的默认动作。你可以通过 JQuery 的preventDefault() 来做到这一点 函数。或者只是&lt;form onsubmit="return false;"&gt; ... &lt;/form&gt;

    【讨论】:

      【解决方案3】:

      document.write的问题,看看what it means

      【讨论】:

        猜你喜欢
        • 2019-07-13
        • 2014-02-05
        • 1970-01-01
        • 1970-01-01
        • 2013-08-18
        • 1970-01-01
        • 2021-03-28
        • 2011-01-13
        • 2020-12-19
        相关资源
        最近更新 更多