2014-01-08 93 views
0

我知道,這樣做是可能的:傳遞參數給jQuery函數

$(document).ready(testing); 

function testing(){ 
    alert('hellow world!'); 
} 

但我怎麼會做出這樣的工作,我想傳遞一個變量的函數:

$(document).ready(testing('hey world!')); 

function testing(message){ 
    alert(message); 
} 
+1

這不是一個jQuery的功能,這簡直是一個jQuery包裝的範圍內的JavaScript函數。 –

+0

你想要這個奇怪的例子嗎? –

回答

2

你可以使用Function.prototype.bind但它配備了一些disad像失去this參考或Event對象的優勢。

$(document).ready(testing.bind(null, 'message')); //First parameter == this; 

function testing(msg){ 
    alert(msg); //Alert message 
} 

,或者你可以做這樣的:

$(document).ready(testing.bind('message')); 

function testing(){ 
    alert(this); //Alert message 
} 

小提琴:http://jsfiddle.net/KedKq/1/

1

您可以使用匿名函數:

$(document).ready(function() { 
    testing('hey world!')); 
}); 

function testing(message){ 
    alert(message); 
}