supertonsky
supertonsky

Reputation: 2733

What's the difference between "click" and "onclick" when creating an element with jQuery?

What's the difference between

$("<a>", {
    "id" : "myId",
    "text" : "my link",
    "href" : "#",
    "onclick" : function() { return false; }
);

and

$("<a>", {
    "id" : "myId",
    "text" : "my link",
    "href" : "#",
    "click" : function() { return false; }
);

?

Upvotes: 11

Views: 10153

Answers (1)

McGarnagle
McGarnagle

Reputation: 102743

Using onclick creates an attribute, and its value should be a string that refers to a function, not an actual function. Using click creates a property on the element, and its value should be the function itself.

So, the first one is written incorrectly; should be like this:

$("<a>", {
    "id" : "myId",
    "text" : "my link",
    "href" : "#",
    "onclick" : "somefunction()"
} );

where "somefunction" is defined in the global scope:

window.somefunction = function() { return false; }

Upvotes: 17

Related Questions