我不想刷新我的页面或控制台! Javascript 表单处理

I don't want my page or console to refresh! Javascript form handling

<form id="myForm">
    <input type="text" value="Try me!">
    <button type="submit">Go</button>
</form>
<script type="text/javascript">
    function init(){
        var form = document.getElementById("myForm");
        form.addEventListener("submit", process, false);
    };
    function process(){
        console.log("Yikes!");
        return false;
    };
    document.addEventListener("DOMContentLoaded", init, false);
</script>

我搜过了,真的。我发现了一些有用的东西,但我被告知要使用事件监听器而不是 "onsubmit" 等。我假设表单提交的默认行为是重新加载页面,但我认为 return 错误会阻止这个。我发现有效的代码是:

window.onload=function() {
    document.getElementById('my-form').onsubmit=function() {
    /* do what you want with the form */

    // Should be triggered on form submit
    console.log("Yipee!");
    // You must return false to prevent the default form behavior
    return false;
  }
}

非常感谢在我的学习过程中提供的任何帮助。

使用preventDefault方法。

function init(){
    var form = document.getElementById("myForm");
    form.addEventListener("submit", process, false);
};
function process(e){
    console.log("Yikes!");
    e.preventDefault()
    return false;
};
document.addEventListener("DOMContentLoaded", init, false);

试试这个:

<form id="myForm">
    <input type="text" value="Try me!">
    <button type="submit">Go</button>
</form>
<script type="text/javascript">
    function init()
    {
        var form=document.getElementById("myForm");
        form.addEventListener("submit", process, false);
    }
    function process(e)
    {
        console.log("Yikes!");
        e.preventDefault();
    }
    document.addEventListener("DOMContentLoaded", init, false);
</script>

window.onload=function()
{
    document.getElementById('myForm').onsubmit=function(e)
    {
        console.log("Yipee!");
        e.preventDefault();
    }
};

You need to use preventDefault() to prevent the form to be submitted..