I have a jQuery onClick
handler, writed with an anonymous function like that:
$("#selector").on("click" function(){
// do something
})
I would generalize the anonymous function extracting the logic in a named function, that drive me to something like:
$("#selector").on("click" namedFunction())
function namedFunction(){
// do something
}
To me seemed a good solution. But there's a drawback since the namedFunction
is executed as soon script is loaded. Here you can test the bad behaviour.
To trigger the onclick function in jQuery, click() method is used. For example, on clicking a paragraph on a document, a click event will be triggered by the $(“p”). click() method. The user can attach a function to a click method whenever an event of a click occurs to run the function.
on() differs from . click() in that it has the ability to create delegated event handlers by passing a selector parameter, whereas . click() does not.
click() shorthand is deprecated at jQuery 3 on() and . trigger() methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods.
jQuery error() Method The error() method triggers the error event, or attaches a function to run when an error event occurs.
Just pass the reference
of that function itself.
Try,
$("#selector").on("click", namedFunction);
You don't need the ()
for your function here:
$("#selector").on("click", namedFunction)
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