2012-04-19 37 views
0

我的PHP文檔末尾有一個變量,在頁腳中。但是,因爲它是模板,所以在每個頁面中創建變量的內容的方式不同。大多數變量的contect的是JS,這看起來是這樣的:用PHP放置JS var

$myVar = ' 
    $(function() { 
    '.$qTip.' 

    $(".delDupe").click(function(){ 
     $(this).parent().find("input").val(""); 
     $(this).remove(); 
    }); 

    function custAxis() { 
     if ($("#axisChk").is(":checked")){ 
      $(".customAxis").show(); 
     } else { 
      $(".customAxis").hide(); 
     } 
    } 

    custAxis(); 
}); 

這是所有JS的只是一個小片段。我想包含這個JS,仍然保留它作爲PHP變量的一部分,但在PHP之外。可能嗎?

$myVar = '?> 
     // my JS 
<? '; 
+0

你試過了嗎?結果是什麼? – tkone 2012-04-19 01:25:23

+1

聽起來像一個AJAX工作 – 2012-04-19 01:26:11

+2

你的底部的例子,打破了一個PHP變量不能這樣做,它會被解釋爲一個字符串。我建議你使用heredoc – 2012-04-19 01:26:55

回答

2

您可以使用此格式:

$myVar = <<<EOD 
Example of string 
spanning multiple lines 
using heredoc syntax. 
EOD; 
+0

但是如何在裏面插入'$ qTip'? – Igor 2012-04-19 01:31:33

+0

沒關係,我可以複製實際的代碼,如果我可以讓其餘的工作。 EOD,哈?從來沒有聽說過...我會給它一個旋風! – santa 2012-04-19 01:32:57

1

您可以用定界符:

<? 
$myVar = <<<END 
$(function() { 
....  
END; 

echo $myVar; 
?> 
0

把JavaScript的成美元的PHP qTip字符串的HTML輸出。它或多或少與你所做的一樣,只是用另一種方式寫的。

$(function() { 
<?=$qTip?> 

$(".delDupe").click(function(){ 
    $(this).parent().find("input").val(""); 
    $(this).remove(); 
}); 

function custAxis() { 
    if ($("#axisChk").is(":checked")){ 
     $(".customAxis").show(); 
    } else { 
     $(".customAxis").hide(); 
    } 
} 

custAxis(); 
}); 
1

你可以用定界符

<?php 
$myVar = <<<EOD 
    $(".delDupe").click(function(){ 
     $(this).parent().find("input").val(""); 
     $(this).remove(); 
    }); 

    $qTip 

    function custAxis() { 
     if ($("#axisChk").is(":checked")){ 
      $(".customAxis").show(); 
     } else { 
      $(".customAxis").hide(); 
     } 
    } 
EOD; 
?> 

或者你可以使用ob_start,打破了PHP的搶輸出作爲一個變量,我這是怎麼加載我所有的意見/ HTML

<?php 
ob_start(); 
?> 
    $(".delDupe").click(function(){ 
     $(this).parent().find("input").val(""); 
     $(this).remove(); 
    }); 

    <?=$qTip;?> 

    function custAxis() { 
     if ($("#axisChk").is(":checked")){ 
      $(".customAxis").show(); 
     } else { 
      $(".customAxis").hide(); 
     } 
    } 
<?php 
$myVar = ob_get_contents(); 
ob_end_clean(); 
echo $myVar; 
?>