Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

return false from jQuery click event

I have click events set up like this:

$('.dialogLink')
    .click(function () {
        dialog(this);
        return false;
    });

The all have a "return false"

Can someone explain what this does and if it's needed?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

When you return false from an event handler it prevents the default action for that event and stops the event bubbling up through the DOM. That is, it is the equivalent of doing this:

$('.dialogLink')
   .click(function (event) {
       dialog(this);
       event.preventDefault();
       event.stopPropagation();
});

If '.dialogLink' is an <a> element then its default action on click is to navigate to the href. Returning false from the click handler prevents that.

As for whether it is needed in your case, I would guess the answer is yes because you want to display a dialog in response to the click rather than navigating. If the element you've put the click handler on does not have a default action on click (e.g., normally nothing happens when you click a div) then you needn't return false because there's nothing to cancel.

If you want to do something in response to the click but let the default navigation continue then do not return false.

Further reading:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...