I try to call a function in jquery with parameter such that
$(document).ready( function() {
$('#id_pros').bind('change', wordCounter('id_pros_wordCountLabel') );
});
function wordCounter(item){
....
}
If I don't pass parameter id_pros_wordCountLabel it works great but now it didn't call wordCounter.
Which part is wrong with my code ?
Thanks
-
1Bind expexts you to pass a reference to a function (or directly, a anonymous function) but instead you execute the function during the "bind" process, which returns undefined, so nothing is bound.roberkules– roberkules2011年06月17日 12:35:41 +00:00Commented Jun 17, 2011 at 12:35
2 Answers 2
.bind() expects a function argument, like this:
$('#id_pros').bind('change', wordCounter);
Note how there are no parentheses on wordCounter. This means that it's a reference to a function, and not an invocation of a function — which is what happens when you add parentheses. Use an anonymous function to solve the problem:
$('#id_pros').change(function ()
{
wordCounter('id_pros_wordCountLabel');
});
(I also changed .bind('change', ...) to .change(...) which is equivalent but more concise.)
Comments
The correct way to do it is:
$(document).ready( function() {
$('#id_pros').bind('change', function() {
wordCounter('id_pros_wordCountLabel');
});
});
Your own code passes the return value of wordCounter (which is called on the spot, and not when the change event fires) to bind. bind expects to receive a function, and wordCounter probably returns something else, so when the change event fires you don't see anything happen.