2013-11-21 71 views
0

我想通過一些PHP到我的jQuery附加功能。我知道我無法直接傳遞PHP,所以我試圖讓PHP變成一個變量,然後在jQuery中調用變量。這可能嗎?將PHP傳遞給jQuery追加函數?

這裏是我到目前爲止(不工作):

function appendElements() { 
var template_dir = "<?php bloginfo('stylesheet_directory'); ?>"; 
if (window.matchMedia("(min-width: 1100px)").matches) { 
jQuery("#container").append("\ 
    <div id='BG' class='bg_images' data-stellar-ratio='.5'>\ 
     <img src='"+template_dir+"/assets/scroll/site/bg_desktop.png'/>\ 
    </div>\ 
    "); 
} 
+2

這的確是可能的,如果** ** javascript代碼會突破PHP解析器。 – adeneo

+0

,如果adeneo說沒有意義,PHP解析器將是任何文件服務爲PHP。這看起來像wordpress,所以你可以把它放在header.php文件的腳本標籤中。 js文件不會解析該文件。 –

+0

您還需要回復'bloginfo'的值:var template_dir =「<?php echo bloginfo('stylesheet_directory');?>」;'或使用PHP的短標籤:var template_dir =「<?= bloginfo ('stylesheet_directory');?>「;' –

回答

0

<head></head>標籤之間添加<script> var template_dir = "<?php bloginfo('stylesheet_directory'); ?>"; </script>

然後運行你的函數,你通常會:

function appendElements() { 
    if (window.matchMedia("(min-width: 1100px)").matches) { 
     jQuery("#container").append("\ 
      <div id='BG' class='bg_images' data-stellar-ratio='.5'>\ 
       <img src='"+template_dir+"/assets/scroll/site/bg_desktop.png'/>\ 
      </div>\ 
     "); 
    } 
}