停止表单提交的一种方法是从JavaScript函数返回false。

当单击提交按钮时,将调用验证函数。我有一个表单验证的案例。如果满足这个条件,我调用一个名为returnToPreviousPage()的函数;

function returnToPreviousPage() {
    window.history.back();
}

我正在使用JavaScript和Dojo工具包。

它不是返回到前一页,而是提交表单。我如何终止这次提交并返回到上一页?


当前回答

例如,如果你在表单上有提交按钮,为了阻止它的传播,只需编写event.preventDefault();在点击提交按钮或进入按钮时调用的函数中。

其他回答

基于@Vikram Pudi的回答,我们也可以用纯Javascript做到这一点

<form onsubmit="submitForm(event)">
    <input type="text">
    <input type="submit">
</form>

<script type="text/javascript">

    function submitForm(event){
        event.preventDefault();


    }
</script>

例如,如果你在表单上有提交按钮,为了阻止它的传播,只需编写event.preventDefault();在点击提交按钮或进入按钮时调用的函数中。

假设你有一个类似的形式

<form action="membersDeleteAllData.html" method="post">
    <button type="submit" id="btnLoad" onclick="confirmAction(event);">ERASE ALL DATA</button>
</form>

下面是confirmAction函数的javascript

<script type="text/javascript">
    function confirmAction(e)
    {
        var confirmation = confirm("Are you sure about this ?") ;

        if (!confirmation)
        {
            e.preventDefault() ;
            returnToPreviousPage();
        }

        return confirmation ;
    }
</script>

这一个工作在Firefox, Chrome, Internet Explorer(edge), Safari等。

如果不是这样,请告诉我

做一件简单的事情有很多困难的方法:

<form name="foo" onsubmit="return false">

禁用提交按钮也可以帮助阻止表单提交。

<input style="display:none" type="submit" disabled>