Returning false from click handler doesn't work in Firefox

前端 未结 3 821
星月不相逢
星月不相逢 2020-12-10 04:21

In the example below, return false does not seem to prevent the default action after the link is clicked (because the page scrolls to the top) in Firefox 3.6 or

相关标签:
3条回答
  • 2020-12-10 04:57

    return false works cross browser, but only for event handlers assigned the "DOM0" way, such as

    document.getElementById("link").onclick = function() {
        alert("Clicked!");
        return false;
    };
    

    For event handlers assigned the DOM Level 2 way via addEventListener(), you have to use preventDefault():

    document.getElementById("link").addEventListener("click", function(evt) {
        alert("Clicked!");
        evt.preventDefault();
    }, false);
    

    For event listeners attached via attachEvent() in IE, either return false or window.event.returnValue = false will do:

    document.getElementById("link").attachEvent("onclick", function() {
        alert("Clicked!");
        return false;
    });
    
    0 讨论(0)
  • 2020-12-10 05:04

    I have had some cross-browser issues with the return false method.

    I have had good luck just replacing the href of the like with the following:

    function removeLink(elementName) {
       var o = document.getElementById(elementName);
       o.href = 'javascript: (function(){})();';
       o.target = "_self";
    }
    

    I have found that this empty function in the href property has been the easiest.

    I have added the target _self part because when I develop I occasionally have these links (that I want to be hover boxes) open in a new window/tab. They need to be pointed at the current window to truly do nothing ... lol.

    Hope this helps whomever.

    Brynn

    0 讨论(0)
  • 2020-12-10 05:13

    You say "preventDefault() helps" but you say it doesn't work? I'm not sure I understand. Have you tried this:

    addEventListener("DOMContentLoaded", function() {
        document.getElementById("link").addEventListener("click", function(e) {
            alert("Clicked!");
            e.preventDefault();
            return false;
        }, false);
        alert("Click handler bound!");
    }, false);
    
    0 讨论(0)
提交回复
热议问题