使用jQuery编辑表单时确认离开页面 [英] Confirm to leave the page when editing a form with jQuery

查看:67
本文介绍了使用jQuery编辑表单时确认离开页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写表单,并且需要像stackoverflow这样的函数:您已经开始写或编辑帖子."

I am coding a form and I need a function like stackoverflow have: "You have started writing or editing a post.".

我已经查看了stackoverflow的代码,以了解它们是如何做到的,但是我根本不了解将其应用于我的简单表单.这就是他们对question.js的看法:

I've looked through the code of stackoverflow to see how they do it but I don't get it at all to apply to my simple form. This is what they have on question.js:

function initNavPrevention(b) {
    if (b.which == "undefined") {
        return
    }
    var a = $("#wmd-input");
    a.unbind("keypress", initNavPrevention);
    setConfirmUnload("You have started writing or editing a post.", a)
}

其中一个函数触发了此操作(我不知道c是什么):

One of the functions triggers this (I don't know what c is):

if (c) {
    e.keypress(initNavPrevention)
}

最后,我想他们有setConfirmUnload(null);来禁用它.

And finally they have setConfirmUnload(null); to disable it I suppose.

我的情况很简单.我有一个页面,我在其中通过AJAX加载<form />,并且我想防止在加载此表单时不单击SUBMIT按钮就离开该页面,或者如果用户单击取消",该表单将被禁用,并且不会弹出该预防措施.

My case is simple. I have a page where I load a <form /> via AJAX and I want to prevent when this form is loaded to leave the page without click on the SUBMIT button or if the user clicks CANCEL the form is disabled and the prevention will not popup.

有了此代码,有人可以告诉我如何将其包含在我的网站中吗?

Having this code, can someone tell me how I can include it on my website?

这是我的AJAX函数,用于加载表单:

This is my AJAX function to load the form:

$("#projects_historics_edit_part_1").click(function(){
    $("#ajax-loader").fadeIn('normal');

    $.ajax({
        url: BASE_URL + 'projects/ajax/get_historics_edit_part_1/' + PROJECT_ID,
        type: "POST",
        success: function(data) {
            $("div#projects_historics_part_1").html(data);

            $("#client").autocomplete(client_autcomplete_options);

            var inicofin = $("#initdate, #findate").datepicker(initdate_datepicker_options);
        }
    });

    $("#ajax-loader").fadeOut("normal");

    return false;    
});

提前谢谢!

推荐答案

您可以使用 window.onbeforeunload 像这样:

You can do this using window.onbeforeunload like this:

window.onbeforeunload = function() {
    return 'Are you sure you want to navigate away from this page?';
};

因此,在您的代码中,应将其放在$.ajax调用的success回调中.

So in your code, you would put that inside the success callback of your $.ajax call.

要取消确认,您可以执行以下操作:

To unset the confirmation, you can do this:

window.onbeforeunload = null;

此外,请参见以下答案:如何覆盖OnBeforeUnload对话框并用我自己的对话框替换?

Also, see this answer: How can I override the OnBeforeUnload dialog and replace it with my own?

这篇关于使用jQuery编辑表单时确认离开页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆