Reputation: 649
Consider the following two code examples:
// Example 1
$('#myButton').click(function() {
alert('I was clicked');
});
// Example 2
$('#myButton').click(
alert('I was clicked');
);
Why specifically does example 2 not work?
Upvotes: 0
Views: 45
Reputation: 262949
Your second code snippet does not work because it invokes the alert() method of the window
object (which returns undefined
), and passes the value it returns (thus, undefined
) as a handler to the click() method of a jQuery object.
undefined
is not a valid event handler, so click()
ignores it and does nothing (except maybe log an error to your console, depending on your browser).
Your first code snippet passes a genuine function that, in turn, invokes alert()
. Since it is a function, it can be registered as an event handler.
Upvotes: 4