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; }
);
?
click is a function on HTML elements you can call to trigger their click handlers: element. click(); onclick is a property that reflects the onclick attribute and allows you to attach a "DOM0" handler to the element for when clicks occur: element.
jQuery click() MethodThe click event occurs when an element is clicked. The click() method triggers the click event, or attaches a function to run when a click event occurs.
The difference is that the first ( click ) is an event listener, and the second ( onclick ) is an event handler content attribute.
addEventListener can add multiple events to a particular element. onclick can add only a single event to an element. It is basically a property, so gets overwritten.
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; }
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