我正在开发一个动态生成的企业应用程序,我们无法控制代码 . 表单中的大多数控件都有以下与之关联的代码
<select name="s_10_1_1_0" onchange = 'SWESubmitForm(document.SWEForm10_0,s_5,"","1-E0RHB7")' id='s_10_1_1_0' tabindex=1997 >
<input type="text" name='s_10_1_11_0' value='' onchange = 'SWESubmitForm(document.SWEForm10_0,s_7,"","1-E0RHB7")' id='s_10_1_11_0' tabindex=1997 maxlength="30">
当用户尝试使用页眉或页脚中的链接导航到其他页面时,我们想要提供一个ok取消对话框 .
我习惯使用以下代码绑定onbeforeunload事件并向用户显示ok取消对话框 .
//this identifies the unique page name
var viewName = $('input[name="SWEView"]').val();
// if I am on desired page bind the event so that now dialog is presented to user
if(viewName == "XRX eCustomer Create Service Request View"){
$(window).bind('beforeunload', function(){
return 'Your Inquiry has not been submitted yet.';
});
}
但问题是每次用户更改表单中任何字段的值时都会出现此对话框(我认为这是由于onchange事件存在SWESubmitForm代码) .
如果用户点击窗体外的任何其他链接,或者换句话说,将onbeforeunload绑定到页面上的选择性事件(包括关闭窗口),我想onbeforeunload对话框来 .
请帮忙
1 回答
.onbeforeunload()
是全球性的 . 你只能通过一些离开页面的方式触发它 . 如果安装了事件处理程序,无论查看者如何离开页面,它都会触发 .您可以跟踪自己的内部状态,并决定是否在
onbeforeunload()
处理程序中提示任何内容,或者只返回任何内容(因此不会提示) .所以,你可以有这样的代码:
Update
由于谷歌收视率很高,因此值得注意的是,这个答案不再适用 .
请注意,绑定事件中不再有'on' . 在更高版本的jQuery中使用之前的
onbeforeunload
将不会发生任何事情 .