I have a function myFunc that can be triggered 2 different ways: by clicking div1 or div2.
- If the click came from div2, I’d like to pass some parameters to the function at the time of the call.
- Also, in both cases, I need a reference to the item that was clicked:
$(this).
I’ve tried this code, but the second version (where I’m passing the parameters) gets triggered automatically even without me clicking anything. What am I doing wrong, and do I need to pass this as a parameter in both cases?
$('#div1').live('click', myFunc);
$('#div2').live('click', myFunc('param1 value', 'param2 value'));
function myFunc(param1, param2){
console.log('inside myFunc');
}
Your second line is immediately executing
myFunc. Instead, wrap it in an anonymous function:You’ll need to use
applyorcallto preserve the original context (otherwisethisinmyFuncwill be the global window object instead of the clicked element).