【问题标题】:How to prevent the page from reloading or refreshing on cancel option?如何防止页面在取消选项时重新加载或刷新?
【发布时间】:2014-03-02 23:35:35
【问题描述】:

当用户单击“取消”选项时,我试图阻止页面重新加载或提交。我环顾了一下stackoverflow,对我遇到的问题有相同的语法,但我尝试了这样的事情,它仍然提交并在取消选项时重新加载页面。如何阻止它执行任何操作并让页面保持原样取消?

JavaScript 代码:

// create an input element
var frm = document.getElementById("result");
var submitBtn = document.createElement("input");
submitBtn.type = "submit";
submitBtn.value = "Confirm Purchase";
frm.appendChild(submitBtn);
submitBtn.addEventListener('click', function()
{
    // confirm the data
    var submitQ = confirm('Are you sure you want to submit your DSLR selections?');
    if(submitQ)
    {
    alert('Your query has been submitted! Have a great day! :)');
    }
    else document.getElementById("result").onsubmit = false; // prevent the page from refreshing on Cancel option
});

HTML 代码:

<form id="result" onsubmit="true">
    <!--Store User Selection Text Node Element Here-->
        <!--<p>Your DSLR budget range selected was:</p>
    <p>The DSLR brand you selected was:</p>
    <p>The type of photography you selected was:</p>
    <p>The type of lenses you selected was:</p>
    <input type="submit" value="Confirm Purchase"/>
    <input type="button" value="Reset All"/>-->
</form>

【问题讨论】:

    标签: javascript forms submit confirm onsubmit


    【解决方案1】:

    更改您的事件处理程序以处理表单onsubmit 事件而不是提交按钮click 事件。如果用户取消,则返回 false:

    frm.onsubmit = function(){
        // confirm the data
        var submitQ = confirm('Are you sure you want to submit your DSLR selections?');
        if(submitQ)
        {
        alert('Your query has been submitted! Have a great day! :)');
        } else {
           // prevent the page from refreshing on Cancel option
           return false;
        }
    };
    

    见小提琴 -> http://jsfiddle.net/LGd2f/

    【讨论】:

    • 你确定吗?您似乎没有在 loooong fiddle 中使用 onsubmit 处理程序 :) 这是一个更新,您可以自己查看页面是否重新加载 -> jsfiddle.net/BS55A
    • 谢谢,终于明白了!似乎submitBtn.addEventListener 无法识别该事件,因为它是一个按钮,仅此而已。与使用 frm.onsubmit 相反,并在表单具有 onsubmit 的事件中使用该值。谢谢,我会记住这一点!
    【解决方案2】:

    也许您应该尝试将事件附加到表单提交事件而不是单击按钮,然后只需 return falsereturn true

    【讨论】:

      猜你喜欢
      • 2018-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      • 2016-01-18
      • 2020-04-17
      相关资源
      最近更新 更多