简体   繁体   English

如何确定JavaScript中window.onbeforeunload中的哪个控件导致了该事件

[英]How to determine which control in window.onbeforeunload in javascript caused the event

I have set up in javascript: 我已经在javascript中设置了:

var    onBeforeUnloadFired = false;

window.onbeforeunload = function (sender, args)

{
   if(window.event){
      if(!onBeforeUnloadFired) {
         onBeforeUnloadFired = true;
         window.event.returnValue = 'You will lose any unsaved changes!'; //IE
      }
   }
   else {
      return 'You will lose any unsaved changes!'; //FX
   }

   windows.setTimeout("ResetOnBeforeUnloadFired()", 1000);
}

function ResetOnBeforeUnloadFired() {
   //Need this variable to prevent IE firing twice.
   onBeforeUnloadFired = false;
}

I'm trying to achieve an edit screen where the user is warned before navigating away. 我正在尝试实现一个编辑屏幕,在导航屏幕之前,该用户会在离开前得到警告。 It works fine except I get the pop up for normal post backs of button clicks. 它工作正常,除了我弹出按钮单击后的常规帖子。 I'm hoping to avoid this so I'm figuring if I could determine which button was pressed it would work. 我希望避免这种情况,因此我想确定是否可以确定按下哪个按钮。

Does anybody know how to determine which button was pressed in the windows.onbeforeunload? 有人知道如何确定在windows.onbeforeunload中按下了哪个按钮吗?

Alternatively anyone know a better approach to what I'm trying to achieve? 或者,有人知道我要达到的更好的方法吗?

Another method, if you can't "control" that deep you controls, is to mark somewhat the "good controls", that is the ones which should not trigger the away-navigation logic. 如果您不能“控制”您控制的深处,另一种方法是在某种程度上标记“良好的控制”,即那些不应触发“离开导航”逻辑的控制。 That is easily achievable setting a global javascript variable such as 设置全局javascript变量(例如,

var isGoodLink=false;
window.onbeforeunload = function (e) {
  var message = "Whatever";
  e = e || window.event;
  if (!isGoodLink) {
  // For IE and Firefox
  if (e) {
    e.returnValue = message;
  }
  // For Safari
  return message;
  }
};
function setGoodLink() {
  isGoodLink=true;
}

And add the setGoodLink function on the events you want to keep safe: 并在要确保安全的事件上添加setGoodLink函数:

<button type="button" onclick="javascript:setGoodLink() ">I am a good button!</button>

Solved this by putting into an update panel all edit items TextBoxes etc. 通过将所有编辑项TextBoxes放入更新面板来解决此问题。

Now the windows.onbeforeunload only fires for components external to this. 现在,仅针对此外部组件触发windows.onbeforeunload。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM