开发者

When should I use return false in jquery function?

开发者 https://www.devze.com 2023-03-03 22:46 出处:网络
I found lots of functions like this one: $(function() { $(\"body a\").click(function() { alert(this.innerHTML);

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 ret开发者_运维技巧urn false in jquery function and don't know what's the use of it?


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.


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.


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

精彩评论

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