[英]Pass parameter to a jquery function
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);
}
You could use Function.prototype.bind
but it come with some disadvantages like losing the this
reference or the Event
object. 您可以使用Function.prototype.bind
但是它具有一些缺点,例如丢失this
引用或Event
对象。
$(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/ 小提琴: http : //jsfiddle.net/KedKq/1/
You can use an anonymous function: 您可以使用匿名函数:
$(document).ready(function() {
testing('hey world!'));
});
function testing(message){
alert(message);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.