Using jQuery, I set a link tag's click handler like this:
$('#lnk').click(handleClick);
handleClick does something like this:
function handleClick() {
var $this = $(this);
...
}
Now I have a need to directly call handleClick() outside of #lnk being clicked. Is there a way for me to set this
when calling handleClick?
You can use apply()
or call()
:
handleClick.call(theElementThatShouldBeThis);
But of course theElementThatShouldBeThis
must be a DOM element or something that is accepted as input for jQuery()
.
And it becomes more tricky if you are accessing the event
element inside handleClick
. But I will just assume you don't ;)
You can also always execute the event handler in the context of #lnk
by calling $('#lnk').click()
(which simulates a click).
I think you're looking for "call" or "apply":
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply
var result = fun.apply(thisArg, [argsArray]);
or
var result = fun.call(thisArg[, arg1[, arg2[, ...]]]);
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