zhuanzhou
zhuanzhou

Reputation: 2453

When should I use return false in jquery function?

I found lots of functions like this one:

$(function() {
    $("body a").click(function() {
        alert(this.innerHTML);
        return false;
    });
});

What's the difference between this and $(this) in jquery?

They all have a line return false; - I don't know when I should use return false in jquery function and don't know what's the use of it?

Upvotes: 37

Views: 61944

Answers (3)

gruntled
gruntled

Reputation: 2694

According to jQuery Events: Stop (Mis)Using Return False (archived link), returning false performs three tasks when called:

  1. event.preventDefault();
  2. event.stopPropagation();
  3. Stops callback execution and returns immediately when called.

The only action needed to cancel the default behaviour is preventDefault(). Issuing return false; can create brittle code. Usually you'd want just this:

$("a").on( 'click', function (e) {
    // e == our event data
    e.preventDefault();
});

And secondly "this" is a DOM element in javascript and "$(this)" is a jQuery element that references the DOM element. Read more on the topic at jQuery's this: demystified.

Upvotes: 66

Rob Cowie
Rob Cowie

Reputation: 22619

In the scope of the click handler, this is the unwrapped DOM element. $(this) wraps it and returns a jQuery element. It is common practice to wrap this once and make it available within the scope as that, or often $this (prefixing variable names with $ is a convention to indicate a jQuery element).

Your example could therefore be written as

$(function() {
    $("body a").click(function() {
        var $this = $(this);
        alert($this.html());
        return false;
    });
});

Upvotes: 4

Kon
Kon

Reputation: 27441

You're clicking on an anchor, whose default behavior is to navigate somewhere. Returning false may be an attempt to prevent the navigation and keep user on current page/view.

Upvotes: 11

Related Questions