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?
Return statements, in programming languages, are used to skip the currently executing function and return to the caller function. Return statements may/may not return any value. Below is the example of a return statement in JavaScript.
Using return causes your code to short-circuit and stop executing immediately. The first return statement immediately stops execution of our function and causes our function to return true . The code on line three: return false; is never executed.
When we write return false; then on click of “Click here !” does not redirect to anywhere.
According to jQuery Events: Stop (Mis)Using Return False (archived link), returning false
performs three tasks 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With