10

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

?

supertonsky
  • 2,563
  • 6
  • 38
  • 68

1 Answers1

16

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; }
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • It should be `"onclick" : "somefunction()"`, if you want the function to be called. – Musa Dec 13 '12 at 04:28
  • @dbaseman good answer. Though it can still be improved by explaining the difference between an attribute and a property in this context and why it would still work if you assign a function to onclick attribute instead of a string. – supertonsky Dec 13 '12 at 05:58