I am trying to call a function with parameters using jQuery's .click, but I can't get it to work.
This is how I want it to work:
$('.leadtoscore').click(add_event('shot'));
which calls
function add_event(event) {
blah blah blah }
It works if I don't use parameters, like this:
$('.leadtoscore').click(add_event);
function add_event() {
blah blah blah }
But I need to be able to pass a parameter through to my add_event
function.
How can I do this specific thing?
I know I can use .click(function() { blah }
, but I call the add_event
function from multiple places and want to do it this way.
Set javaScript object to onclick element:
get Object from "this" element:
I get the simple solution:
My mean is that pass the value
onclick
event to thejavascript function sendData()
, initialize to the variable and take it by the jquery event handler method.This is possible since at first
sendData(valueid)
gets called and initialize the value. Then after jquery event get's executed and use that value.This is the straight forward solution and For Detail solution go Here.
Yes, this is an old post. Regardless, someone may find it useful. Here is another way to send parameters to event handlers.
You need to use an anonymous function like this:
You can call it like you have in the example, just a function name without parameters, like this:
But the
add_event
method won't get'shot'
as it's parameter, but rather whateverclick
passes to it's callback, which is theevent
object itself...so it's not applicable in this case, but works for many others. If you need to pass parameters, use an anonymous function...or, there's one other option, use.bind()
and pass data, like this:And access it in
add_event
, like this:For thoroughness, I came across another solution which was part of the functionality introduced in version 1.4.3 of the jQuery click event handler.
It allows you to pass a data map to the event object that automatically gets fed back to the event handler function by jQuery as the first parameter. The data map would be handed to the
.click()
function as the first parameter, followed by the event handler function.Here's some code to illustrate what I mean:
I know it's late in the game for this question, but the previous answers led me to this solution, so I hope it helps someone sometime!
If you call it the way you had it...
...you would need to have
add_event()
return a function, like...The function is returned and used as the argument for
.click()
.