Say I have the following code
$("p").bind("click", function(){
alert( $(this).text() );
});
When the user clicks the button <p>, a warning appears. Good thing I use the keyword "this".
Now I want to get rid of the anonymous function (using it several times per script);
$("p").bind("click", myfunction());
myfunction(){
alert( $(this).text() );
}
Now this refers to the window. How can i fix this?
Update:
Proposed Respondent Solution That Actually Works
$(function(){
$("p").bind("click", function() { myfunction($(this));});
function myfunction(elem)
{
alert( elem.text() );
}
});
This is good, but you end up creating a new function every time a line of code is called, no?
source
share