天天看點

js阻止表單送出的兩種方法

<body>
    <form action="clock.html" method="post" onsubmit="return checkLength()">
        <p>name:<input type="text" name="user" id="user"></p>
        <input type="submit" id="submit" name="submit"> 
    </form>
</body>
</html>      

~~~

clock.html是一個時鐘頁面。

    第一種方法:利用event的阻止預設事件機制,頁面載入之後獲得submit元素,然後為submit注冊click響應函數,參數為event事件。

在使用者點選submit觸發響應函數後,直接event.preventDefault();阻止表單轉跳的預設事件。