2013-10-24 49 views
0

我試圖做下面的JavaScript函數:麻煩從PHP調用

<html> 
<script type="text/javascript" src="jquery.js"></script> 

<a id="random">before</a> 
<script> 
function test(a) 
    { 
     document.getElementById('random').innerHTML="after with variable passed in"; 
    } 
function test2() 
    { 
     document.getElementById('random').innerHTML="after without variable passed in"; 
    } 
</script> 
<?php $sample = "hi"; ?> 

<button onClick="test(<?php echo $sample;?>)">withVariable</button> 

<button onClick="test2()">withoutVariable</button> 
</html> 

如果我點擊「withoutVariable」按鈕,功能測試2()獲取完美的,因爲沒有變量將傳入調用。但是,如果我點擊「withVariable」按鈕,功能測試(a)永遠不會因爲某種原因而被調用。任何想法我在這裏做錯了嗎?

回答

3

由於$sample是一個字符串,你需要用''

<button onClick="test('<?php echo $sample;?>')">withVariable</button> 
+0

哇,我希望我早些時候問過..這麼小的一個錯誤 – SKLAK

0

圍住它,如果你傳遞一個字符串變量,那麼你需要添加引號圍繞價值,像這樣:

<button onClick="test('<?php echo $sample;?>')">withVariable</button>