问题
I have the following Jquery function to notify the user with a prompt when they have unsaved changes (similar to how SO does it) and are trying to leave the current screen.
<!-- in my aspx page -->
<script type="text/javascript" language="javascript">
window.onbeforeunload = function()
{
if (HasPendingUpdates())
{
return "Changes you have made will not be saved.";
}
}
</script>
This works as expected and shows the message box when the user tries to click a href to browse away or use the back button etc. The problem I am having is that one of my links is a asp:LinkButton
because it needs to fire off some server side code before leaving the page. When the user clicks this LinkButton
they get the prompt twice.
Scenarios:
- User clicks the
LinkButton
- Prompt appears and user clicks the cancel button.
Prompt disappears and user is still on screen. GOOD.
User clicks the
LinkButton
- Prompt appears and clicks the OK button.
- Prompt disappears and the same prompt shows again.
- User clicks OK again.
- Prompt disappears and user moves to the next screen and all is good.
So why am I getting the second prompt??? How is the OnBeforeUnload firing twice?
回答1:
I had a similar problem, however, I didn't want to fire onbeforeunload for LinkButtons at all, therefore I used the following for every LinkButton on the .aspx page:
OnClientClick="eval(this.href);return false"
Functionality of the LinkButtons wasn't crippled, since all they did was supplying a Command with CommandArgument for the codebehind to handle...
回答2:
Adding handlers with jQuery stacks them. If you're assigning a handler with some jQuery function for your hrefs and then assigning it again for your linkbutton, there will be two handlers in place.
Check how often you are binding the onunload handler, and make sure that you're either unbinding previous handlers or only doing it once.
回答3:
Here is how to fix this:
var checkChangesEnabled = true;
window.onbeforeunload = confirmExit;
function confirmExit() {
if (checkChangesEnabled) {
event.returnValue = "Changes you have made will not be saved.";
disableCheck();
}
}
function disableCheck() {
checkChangesEnabled = false;
setTimeout("enableCheck()", "100");
}
function enableCheck() {
checkChangesEnabled = true;
}
来源:https://stackoverflow.com/questions/2239456/why-is-onbeforeunload-firing-twice-with-asplinkbutton