避免在用户单击超链接时留下页面确认

Avoid leaving page confirmation when user clicks on hyperlinks

本文关键字:确认 超链接 用户 单击      更新时间:2023-09-26

此方法在用户离开当前页面时带来确认消息:

window.addEventListener("beforeunload", function (e) {
              var confirmationMessage = "¿Seguro?";
              e.returnValue = confirmationMessage;     // Gecko, Trident, Chrome 34+
              return confirmationMessage;              // Gecko, WebKit, Chrome <34
        });

这也包括点击链接,这是正常的,因为它也会离开页面。

正如我已经在其他网站上看到的那样,Javascript方法可以避免此消息在超链接单击时出现?

如果e.returnValue不是空字符串,则会出现确认。您应该检查哪个对象启动了事件,并相应地设置该值:

   window.addEventListener("beforeunload", function (e) {
          var confirmationMessage = "";
          // Only set the message when the target wasn't a link
          if(e.target.nodeName !== "A"){
              confirmationMessage = "¿Seguro?";
          }
          e.returnValue = confirmationMessage;     // Gecko, Trident, Chrome 34+
    });