Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

javascript - 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!");
      return false;
    }, false);
    alert("Click handler bound!");
  }, false);
</script>

<div style="margin-top: 1200px;">
  <a id="link" href="#">Click me!</a>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...