在 Javascript 中实现后退按钮“警告"以在 Flex 中使用 [英] Implement a Back-Button 'Warning' in Javascript for use in Flex

查看:24
本文介绍了在 Javascript 中实现后退按钮“警告"以在 Flex 中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Flex 应用程序,我想在用户点击后退按钮时向用户发出警告,以免他们错误地离开应用程序.我知道由于跨浏览器不兼容,这不能完全在 Actionscript 中完成.我正在寻找的只是用于捕获后退按钮的 Javascript 实现.

I have a Flex application where I want to give the user a warning if they hit the back-button so they don't mistakenly leave the app. I know this can't be done entirely in Actionscript due to cross-browser incompatibility. What I'm looking for is just the Javascript implementation to catch the back-button.

有没有人有一个简单的非库跨浏览器脚本来捕捉后退按钮?我似乎找不到显示示例的帖子.

Does anyone have a simple non-library cross-browser script to catch the back-button? I can't seem to find a post that shows an example.

推荐答案

您可以使用 window.onbeforeunload 事件.

window.onbeforeunload = function () {
   return "Are you sure you want to leave my glorious Flex app?"
}

用户可以按确定离开,取消留下.

The user can press okay to leave, cancel to stay.

正如您所说,只要页面发生变化,就会发出警报.为了确保它只在点击后退按钮时发生,我们必须在他们离开页面时从自然的、预期的来源中消除警报消息.

As you stated, this throws the alert any time the page changes. In order to make sure it only happens on a back button click, we have to eliminate the alert message whenever they're leaving the page from natural, expected sources.

var okayToLeave = false;

window.onbeforeunload = function () {
   if (!okayToLeave) {
   return "Are you sure you want to leave my glorious Flex app?"
   }
}

function OkayToLeave() {
    okayToLeave = true;
} 

您有责任在用户点击按钮或链接时将变量设置为 true,以便他们自然地离开该页面.我会为不显眼的 javascript 使用一个函数.

You'll have the responsibility of setting the variable to true whenever they click a button or link that will take them from that page naturally. I'd use a function for unobtrusive javascript.

在 DOM 中设置您的事件处理程序:

Set your event handlers in the DOM ready:

referenceToElement.addEventListener('onClick', OkayToLeave(), false);

这是未经测试的,但应该为您指明正确的方向.虽然这样做可能看起来很麻烦,但我认为它的功能更完整.它涵盖了用户可能点击收藏夹或从外部应用程序重定向的情况.

This is untested, but should point you in the right direction. Although it may seem like a nuisance to do this, I imagine it's more complete functionality. It covers the cases where a user may click on a favorite, or be redirected from an external application.

这篇关于在 Javascript 中实现后退按钮“警告"以在 Flex 中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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