I know that doing this is possible:
$(document).ready(testing);
function testing(){
alert('hellow world!');
}
But how would I make something like this work where I want to pass a variable to the function:
$(document).ready(testing('hey world!'));
function testing(message){
alert(message);
}
asked Jan 8, 2014 at 18:56
Austin Lovell
1,0593 gold badges18 silver badges29 bronze badges
-
1That's not a jQuery function, it is simply a JavaScript function within the scope of a jQuery wrapper.Diodeus - James MacFarlane– Diodeus - James MacFarlane2014年01月08日 18:58:30 +00:00Commented Jan 8, 2014 at 18:58
-
In what weird case would you want this?Anyone– Anyone2014年01月08日 19:11:58 +00:00Commented Jan 8, 2014 at 19:11
2 Answers 2
You could use Function.prototype.bind but it come with some disadvantages like losing the this reference or the Event object.
$(document).ready(testing.bind(null, 'message')); //First parameter == this;
function testing(msg){
alert(msg); //Alert message
}
or you can do it like this :
$(document).ready(testing.bind('message'));
function testing(){
alert(this); //Alert message
}
Fiddle : http://jsfiddle.net/KedKq/1/
answered Jan 8, 2014 at 19:08
Karl-André Gagnon
33.9k5 gold badges53 silver badges77 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You can use an anonymous function:
$(document).ready(function() {
testing('hey world!'));
});
function testing(message){
alert(message);
}
jb.
24.1k18 gold badges102 silver badges139 bronze badges
answered Jan 8, 2014 at 18:58
cyberwombat
40.6k43 gold badges190 silver badges269 bronze badges
Comments
lang-js