2011-04-16 54 views
0

嗯,我知道我可以做到這一點與jquery,但我想不使用JavaScript,而是使用PHP。也從中學習。我怎麼能追加一行代碼到一個HTML元素使用PHP

我有一個文件夾層次這樣

modules 
|-navagation 
    |-js 
     |-nav.js 

,我想找到一種方法來追加一條.js文件的

<head></head> 

這樣

<html> 
    <title></title> 
    <head> 
     <script scr="jquery.js"></script> 
     <script src="nav.js"></script> 
    </head> 
</html> 

我的目標是我想上傳模塊到我的模塊文件夾,並讓PHP自動提取並從m中加載資源odules。

我正在努力的一件事是我通過Smarty使用.tpl加載我的文件來顯示我的標記。這就是我正在處理的唯一困境。

我原來的方法是這樣的,但是因爲我用模板文件來做它,所以我很茫然。

ob_start(); 
include(THEME_PATH . "/index.html"); 
$content = ob_get_contents(); 
ob_end_clean(); 

// Scripts to include 
$scripts = BaseHelper::include_script("http://code.jquery.com/jquery-1.4.2.min.js"); 
$scripts .= BaseHelper::include_script("js/jquery.sound.js"); 
$scripts .= BaseHelper::include_script("js/jquery.jblock.js"); 
$scripts .= BaseHelper::include_script("js/init.js"); 

// Add scripts to theme 
echo str_replace("</head>", $scripts . "\n</head>", $content); 
+0

我不完全理解你的問題。但嘗試'' – Khez 2011-04-16 08:11:03

+1

*(related)* [最佳解析方法](http://stackoverflow.com/questions/3577641/best-methods -to-parse-html/3577662#3577662) – Gordon 2011-04-16 08:11:09

+0

如果你想修改DOM並且已經知道jQuery,那麼你可以使用phpQuery(見上面的鏈接)。但是,根據您的模板,將腳本內容傳遞到模板而不是更改DOM可能更容易。基本上,當你要用DOM修改模板時,幾乎不需要使用Smarty,因爲DOM可以完全替代Smarty。 – Gordon 2011-04-16 08:12:27

回答

0

我會變成你的index.html模板頁到一個PHP頁面,包括模板之前創建腳本之前變種,然後從包含的模板文件中使其:

ob_start(); 
// Scripts to include 
$scripts = BaseHelper::include_script("http://code.jquery.com/jquery-1.4.2.min.js"); 
$scripts .= BaseHelper::include_script("js/jquery.sound.js"); 
$scripts .= BaseHelper::include_script("js/jquery.jblock.js"); 
$scripts .= BaseHelper::include_script("js/init.js"); 
include(THEME_PATH . "/index.php"); 
$content = ob_get_contents(); 
ob_end_clean(); 

指數.php:

<head> 
<?php echo $scripts ?> 
</head> 
相關問題