开发者

Returning false from click handler doesn't work in Firefox

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 Chrome 10 but works in Internet Explorer.

Using event.preventDefault() does what I need, but I'm wondering why return false does not work with the others.

Side note: I do not need to support Internet Explorer.

<script>
  addEventListener("DOMContentLoaded", function(){
    document.getElementById("link").addEventListener("click", function(){
      alert("Clicked开发者_如何学Python!");
      return false;
    }, false);
    alert("Click handler bound!");
  }, false);
</script>

<div style="margin-top: 1200px;">
  <a id="link" href="#">Click me!</a>
</div>


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;
});


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);


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜