开发者

Jquery help needed for onbeforeunload event

I am using jquery onbeforeunload event in asp.net application. If i write event as given below then its working fine and display confirm dialog box.

var vGlobal = true;
var sMessage = "Leaving the page will lost in unsaved data!";

[ Working ]

> window.onbeforeunload = function() {
>   if (vGlobal == false) return
> sMessage; }

but its not working if i use bind method like as given below

[ Not working ]

$(window).bind("beforeunload", function(e) {
    if (vGlobal == false)
        return sMessage;
});

Anybody suggest me why its not working.Is there any difference between these two methods.

Code on aspx:

<asp:TextBox ID="txtName" runat="开发者_开发技巧server"></asp:TextBox>

CLICK ON THIS LINK TO SEE RUNNING EXAMPLE


See the updated version

You need to bind all the events inside document ready event.


Apart from the fact that vGlobal is true and you are checking if (vGlobal == false), this smells like a $(document).ready() issue.

I.e. you should place the declaration inside a document.ready() handler as shown here:

$(document).ready(function(){
    $(window).bind("beforeunload", function(e) {
        if (vGlobal == false)
            return sMessage;
    });
});


There is no benefit in using jQuery to bind the event to the window - all you are doing is adding the overhead of having jQuery parse the window into a jQuery object, which you aren't even using.

Therefore, using:

window.onbeforeunload = handler;

Is preferable to using jQuery to bind this event.

You can still perform the binding inside of the document ready section:

$(document).ready(function () {
    window.onbeforeunload = handler;
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜