onbeforeunload event is too enthusiastic in IE9

后端 未结 5 1564
萌比男神i
萌比男神i 2021-02-07 00:57

Here\'s some sample test html:



  
    Go nowhere 1<         


        
5条回答
  •  [愿得一人]
    2021-02-07 01:06

    That's a pretty unfortunate bug. It seems you'll have to work around it, and using the hash link method is probably the best way. To avoid taking the user to the top of the page, cancel the event using event.preventDefault() and event.returnValue = false.

    function myClickHandler(e) {
        if (e.preventDefault)
            e.preventDefault();
        e.returnValue = false;
        alert("Not going anywhere!");
    }
    

    Call it like this:

    Go nowhere 1
    

    Edit: You could cancel the event for all the hash-links on your page like this:

    var links = document.links;
    for (var i = 0; i < links.length; i++) {
        var link = links[i];
        if (link.href == "#") {
            if (link.addEventListener) {
                link.addEventListener("click", cancelEvent, false);
            }
            else if (link.attachEvent) {
                link.attachEvent("onclick", cancelEvent);
            }
        }
    }
    function cancelEvent(e) {
        e = e || window.event;
        if (e.preventDefault)
            e.preventDefault();
        e.returnValue = false;
    }
    

    Or with jQuery using just one line of code:

    $("a[href='#']").click(function (e) { e.preventDefault(); });
    

提交回复
热议问题