简体   繁体   English

向野生动物园添加事件侦听器

[英]adding an event listener to safari

I'm trying to add an event listener, via JavaScript for the Safari browser because it doesn't recognize the unload event of a window, apparently. 我正在尝试通过JavaScript为Safari浏览器添加事件监听器,因为它显然无法识别窗口的卸载事件。 So far I have: 到目前为止,我有:

function init()
{
//add unload event handler for safari
if (navigator.userAgent.toLowerCase().indexOf("safari")!=-1) {
    bodyElt = document.getElementsByTagName("body")[0];
     if (bodyElt) {
      bodyElt.addEventListener("unload", onUnloadHandler, false);
    }
}
...

Please do not use browser sniffing. 请不要使用浏览器嗅探。 The following is standards-compliant and works everywhere (if there is W3C DOM support; add wrappers as necessary): 以下内容符合标准,并且可以在任何地方使用 (如果有W3C DOM支持;请根据需要添加包装器):

    …

    <script type="text/javascript">
      function bodyLoad()
      {
        document.body.addEventListener("unload", onUnloadHandler, false);
      }
    </script>
  </head>

  <body onload="bodyLoad()">
    …
  </body>

…

Questions remain, though. 问题仍然存在。 Why are you not using the onunload attribute of the body element in the first place? 为什么首先不使用body元素的onunload属性? And what do you need the unload event listener for? 您需要什么unload事件监听器? Many people think they need unload listeners because they do not handle closures properly, or have that misguided idea of trying to keep visitors at their site. 许多人认为他们需要unload侦听器,因为它们无法正确处理关闭操作,或者存在试图将访问者保留在其站点上的错误观念。

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

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