t;
<option value="4">香蕉</option>
</select><br /><br />
<div id="tip"></div>
</form>
<script type="text/java script">
var $txtOpt = $("#frmTest :selected").text();
$("#tip").html("选中内容为:" + $txtOpt);
</script>
----------------------------------------------------------------
2、正则表达式
这里要做的引擎模板的作用是,替换变量输出。
需要的是模板文件.class,编译源文件.php
--template.class.php
<?php
/*
* 描述:仿smarty模板引擎类文件
*
*/
class template{
private $templateDir; //用来存储源文件所在目录
private $compileDir; //用来存放编译后的文件目录
private $leftTag='{#'; //要替换的对象的标记,smarty默认是{
private $rightTag='#}';
private $currentTemp=''; //用来存储当前正在编译的模板文件名
private $outputHtml; //用来存放currentTemp的HTML代码
private $varpool=array(); //变量池;模板编译时存放变量
public function __construct($templateDir,$compileDir,$leftTag=null,$rightTag=null){
$this->templateDir=$templateDir;
$this->compileDir=$compileDir;
if (!empty($leftTag)) $this->leftTag=$leftTag; //传递左右标记的时候,需要做一下非空的判断
if (!empty($rightTag)) $this->rightTag=$rightTag;
}
//assign函数——把模板中需要用到的变量,放到地址池中,并给定标记
public function assign($tag,$var){
$this->varpool[$tag]=$var;
}
//与上面的assign对应,从地址池中取出变量
public function getVar($tag){
return $this->varpool[$tag];
}
//getSourceTemplate:获取编译的源文件_需要知道文件名,和完整的路径(所以要有拓展名
public function getSourceTemplate($templateName,$ext='.html'){
$this->currentTemp=$templateName;
$sourceFilename=$this->templateDir.$this->currentTemp.$ext;
$this->outputHtml=file_get_contents($sourceFilename);
}
//compileTemplate:编译方法
public function compileTemplate($templateName=null,$ext='.html'){
$templateName=empty($templateName)? $this->currentTemp:$templateName;
//核心代码,正则编译
//\{#\$(\w+)#\}
$pattern='/\{#\$(\w+)#\}/';
//更加清晰的写法$pattern='/'.preg_quote($this->leftTag).' *\$([a-zA-Z_]\w*) *'.preg_quote($this->rightTag).'/';
//核心代码要做的就是找到标记内的东西,然后替换为php可以识别的内容
$this->outputHtml=preg_replace($pattern, '<?php echo $this->getVar(\'$1\')?>', $this->outputHtml);
//注意这里的preg_replace的用法,$1表示匹配的子模式
//下面生成目标文件,同样也需要完整的目标路径
$compiledFilename=$this->compileDir.md5($templateName).$ext;
file_put_contents($compiledFilename,$this->outputHtml);
}
public function display($templateName = null, $ext = '.html') {
$templateName = empty($templateName) ? $this->currentTemp : $templateName;
include_once $this->compileDir.md5($templateName).$ext;
}
}
--index.php
<?php
/*
* 山寨模板引擎测试文件
*/
//包含文件
require_once 'template.class.php';
//获取路径,basedir根目录
$baseDir=str_replace('\\', '/',dirname(__FILE__));
$temp=new template($baseDir.'/source/', $baseDir.'/compliled/');
//变量池
$temp->assign('pagetitle', '山寨版smarty');
$temp->assign('test','imooc女神');
//
$temp->getSourceTemplate('index');
$temp->compileTemplate();
$temp->display();
--几个要注意的是
按照属性+方法,流水线一样编译就好
然后,一些服务要开,否则像我一样,还要调试。。。
祝大家好运。