Let say I have the following code
$("p").bind("click", function(){
alert( $(this).text() );
});
When the user clicks a <p>, an alert show up. What’s good here, is that I make use of the “this” keyword.
Now I want to get rid of the anonymous function (using it multiple time per script);
$("p").bind("click", myfunction());
myfunction(){
alert( $(this).text() );
}
this now refer to Window. How can i do to fix that?
Update:
A suggested solution by answerers that actually works
$(function(){
$("p").bind("click", function() { myfunction($(this));});
function myfunction(elem)
{
alert( elem.text() );
}
});
This is good, but you’ll finish creating a new function every time that line of code is called, no?
You want to pass the original “this” (the context) to the function.
In Javascript, that’s done by using call. Eg, see here
So I modify Jonathon’s answer:
Added:
I looked up jquery bind and Jonathon is right, the context is automatically set to be the original element that you’re adding the event listener to.
I think the real issue is that you’re not passing in the function ref correctly.
Try