JavaScript 和 onbeforeunload?
我有
我想让它这样,如果你按下那个按钮,它也会设置一个变量,这样如果你尝试离开页面,它就会弹出其中一个“您确定要离开此页面”警报可防止人们在上传时意外离开。
不要担心上传完成后取消设置变量,我会补充一点,我只需要你们中的一个聪明的程序员来为我制作一个框架。
谢谢!
I have
<span class="cssButton"><a href="javascript:void(0);" class="buttonBlue" onclick="swfu.startUpload();"> <img src="http://uber-upload.com/img/icons/up_16.png" alt=""/> Uber-Upload! </a></span>
And i want to make it so that if you press that button, it also sets a variable that makes it so that if you try to leave the page, it will pop up one of those "Are you sure you want to leave this page" alerts to prevent people from accidently leaving while there is an upload going on.
Dont worry about unsetting the variable after the upload finishes, i'll add that, i just need one of you smart coders to make me a framework.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将此声明添加到页面:
将 onclick 更改为:
如果
swfu
在完成上传时为您提供某种事件,请将其放在上面:并添加此处理程序:
在浏览器尊重 onbeforeunload 的情况下,会工作的。大多数时候,他们中的大多数人都是这样做的。如果他们没有,那么,你尝试过。请注意,通过使用计数器,您将允许多次上传。
您可能会考虑使用 AttachEvent (IE) 或 addEventListener(标准)(或者像 Prototype 或 jQuery 这样的库来平衡差异)来附加事件而不是使用属性。使用属性(又名 DOM0 处理程序)是相当老式的,并且有一点限制(每个元素每个事件只有一个处理程序)。但它仍然有效。
Add this declaration to the page:
Change your onclick to:
If the
swfu
gives you some kind of event when it's done uploading, put this on it:And add this handler:
Where browsers respect the onbeforeunload, that'll work. And most of them do, most of the time. Where they don't, well, you tried. Note that by using a counter, you're allowing for multiple uploads.
You might consider attachEvent (IE) or addEventListener (standard) (or a library like Prototype or jQuery that evens out the differences for you) for attaching your events rather than using attributes. Using attributes (aka DOM0 handlers) is fairly old-fashioned and a bit limiting (only one handler per event per element). But it does still work.
然后您可以像在
onbeforeunload
事件中一样使用它。然后要使用它,只需对您不想触发它的任何事件使用“isClean”函数(例如,保存),或者您可以将“isDirty”附加到您想要在它们离开之前触发它的任何事件(例如,编辑表单字段)。
Then you use it just like on the
onbeforeunload
event.Then to use it, just use the 'isClean' function to anything you don't want to trigger it(Save, for instance), or you can attach 'isDirty' to any event you want to trigger it before they leave (say, editing a form field).
依赖 onbeforeunload 充其量是粗略的。因为垃圾邮件发送者已经滥用了这种行为,就像您建议人们这样做的能力基本上已被删除一样。
现在,如果关闭事件是通过激活按钮等触发的,则只能响应 onbeforeunload。
Relying on onbeforeunload is sketchy at best. Because spammers have abused the behavior in the same way you're suggesting the ability for people to do this has been basically removed.
You can now only respond to onbeforeunload if the close event was fired from activating a button or such.