37

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?

Gras Double
  • 15,901
  • 8
  • 56
  • 54
zhuanzhou
  • 2,409
  • 8
  • 33
  • 51

3 Answers3

66

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.

Gras Double
  • 15,901
  • 8
  • 56
  • 54
gruntled
  • 2,684
  • 19
  • 16
  • 1
    Archived page as original looks not responding atm: http://web.archive.org/web/20160603125641/http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/ – PF4Public Jan 15 '17 at 22:29
11

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.

Kon
  • 27,113
  • 11
  • 60
  • 86
4

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;
    });
});
Rob Cowie
  • 22,259
  • 6
  • 62
  • 56