beforeunload 事件可以绑定到什么元素上面?

var attention = function (e) {
  var confirmationMessage = "修改尚未保存!";
  console.log(e.);
  (e || window.event).returnValue = confirmationMessage; // Gecko and Trident
  return confirmationMessage; // Gecko and WebKit
};

window.addEventListener('beforeunload', attention);

绑定到 window 上时起效,绑定到其他页面元素则不行,例如

var input = document.querySelector('table>input')
input.addEventListener('beforeunload', attention)
阅读 3.7k
2 个回答

Which HTML tags support the onbeforeunload event?

官方文档对 beforeunload 事件的说明

Let event be a new BeforeUnloadEvent event object with the name beforeunload, which does not bubble but is cancelable.
Dispatch: Dispatch event at the Document's Window object.

官方说,只在 window 对象上支持这个事件

但是我在国外的 w3school 上看到说 body 元素也支持这个事件,然后我就在自己浏览器上试了一下,然而没什么卵用(浏览器:Chrome 53.0)。还是官网的对,只在window 对象上支持这个事件

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题