为什么 OnBeforeUnload 使用 asp:LinkButton 触发两次?
我有以下 Jquery 函数,当用户有未保存的更改(类似于 SO 的做法)并尝试离开当前屏幕时,会提示用户通知。
<!-- 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>
这按预期工作,并在用户尝试单击 href 浏览或使用后退按钮等时显示消息框。我遇到的问题是我的链接之一是 asp:LinkButton
因为它需要在离开页面之前触发一些服务器端代码。当用户单击此 LinkButton
时,他们会收到两次提示。
场景:
- 用户单击
LinkButton
- 出现提示,用户单击取消按钮。
提示消失并且用户仍在屏幕上。好。
用户单击
LinkButton
- 出现提示并单击“确定”按钮。
- 提示消失并再次出现相同的提示。
- 用户再次单击“确定”。
- 提示消失,用户移动到下一个屏幕,一切都很好。
那么为什么我会收到第二个提示??? OnBeforeUnload 如何触发两次?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我遇到了类似的问题,但是,我根本不想为 LinkButtons 触发 onbeforeunload,因此我对 .aspx 页面上的每个 LinkButton 使用了以下内容:
LinkButtons 的功能并没有被削弱,因为它们所做的只是提供带有 CommandArgument 的命令,供代码隐藏处理...
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:
Functionality of the LinkButtons wasn't crippled, since all they did was supplying a Command with CommandArgument for the codebehind to handle...
使用 jQuery 添加处理程序会将它们堆叠起来。如果您为 href 分配带有某些 jQuery 函数的处理程序,然后再次为链接按钮分配它,则会有两个处理程序。
检查绑定 onunload 处理程序的频率,并确保取消绑定以前的处理程序或仅执行一次。
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.
以下是解决此问题的方法:
Here is how to fix this: