完成执行后,Java脚本不需要重新加载页面

时间:2016-11-02 04:37:44

标签: javascript html

我正在进行客户端渲染。我有一个输入标签,我在其中放置一个数字并单击按钮。单击按钮它应该为我的页面添加更多输入标签。但问题是它无缘无故地添加给定数量的输入和重置页面。

请解释一下为什么重播页面?

start

3 个答案:

答案 0 :(得分:1)

  

1.您的onclick事件就像表单提交一样。

     

2.没有返回语句,所以页面重新加载。

     

3.如果您在表单form action="some.php"的操作中应用,则页面会重定向到该页面,如http://firsthtml/some.php

     

4。More reference and demo of from submit

     

5.如果申请返回虚假陈述。它会阻止您的页面休息。并将点击功能应用到表单提交请参阅以下代码

 <HTML>
    <script src="js/main.js"></script>
    //for converting document.getelementbyid() to _()
    <body>
        <div id="form_place">
        <form onsubmit="return addnos()"> <!--return with function-->
            <input name="nos" id='nos' type="text">
            <button  >Enter</button>
        </form>
        </div>
    </body>
    <SCRIPT>
    function addnos(){

        var nos =  _('nos').value;
        for (i=0;i < nos;i++){

        manddy = document.createElement('INPUT');
        manddy.setAttribute("id", 'name'+i+1);
        _('form_place').appendChild(manddy);

        }                           
                              return false; //its will prevent page refresh
    }    
        </SCRIPT>

    </HTML>

答案 1 :(得分:1)

请勿忘记表单中按钮的默认行为是提交。这将触发重新加载。将您的代码更改为:

<HTML>
<script src="js/main.js"></script>
//for converting document.getelementbyid() to _()
<body>
    <div id="form_place">
    <form>
        <input name="nos" id='nos' type="text">
        <button type="button" onclick="addnos()">Enter</button>
    </form>
    </div>
</body>
<SCRIPT>
function addnos(){

    var nos =  _('nos').value;
    for (i=0;i < nos;i++){

    manddy = document.createElement('INPUT');
    manddy.setAttribute("id", 'name'+i+1);
    _('form_place').appendChild(manddy);

    }                           
}    
    </SCRIPT>

</HTML>

答案 2 :(得分:1)

    <HTML>
<script src="js/main.js"></script>
//for converting document.getelementbyid() to _()
<body>
    <div id="form_place">
    <form>
        <input name="nos" id='nos' type="text">
        <button onclick="return addnos()">Enter</button>
    </form>
    </div>
</body>
<SCRIPT>
function addnos(){

    var nos =  _('nos').value;
    for (i=0;i < nos;i++){

    manddy = document.createElement('INPUT');
    manddy.setAttribute("id", 'name'+i+1);
    _('form_place').appendChild(manddy);

    }

    return false;
 }    
    </SCRIPT>

</HTML>

像这样更改您的代码。这将阻止默认行为,因为在HTML中,您调用return someFunc(),因此将返回函数返回的任何内容。并且该函数返回false!所以最后,它会向onclick方法返回false,并且在执行代码时会阻止默认行为。

希望它有所帮助:)

相关问题