注:主要参考网上的一些思想和内容,结合自己的理解,记录下而已
a.html
a.js
a.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JTMA</title>
<script type="text/javascript" src="../js/jquery/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="a.js"></script>
</head>
<body onload="test()">
<div>
<table>
<tr>
<td>通知</td>
<td id="notice">
<ul>
<li>$title$ <span>$data$</span></li>
</ul>
</td>
</tr>
<tr>
<td>国内新闻</td>
<td id="inside_news">
<ul>
<li>$title$ <span>$data$</span></li>
</ul>
</td>
</tr>
<tr>
<td>国外新闻</td>
<td id="outside_news">
<ul>
<li>$title$ <span>$data$</span></li>
</ul>
</td>
</tr>
</table>
</div>
</body>
</html>
a.js
/**
* 比如数据库的字段设计为:
* id 主键自增
* title 主题
* data 发布日期
* type 类型(通知、国内新闻、国外新闻)
*/
String.prototype.temp = function(obj) {
//返回替换后的值
return this.replace(/\$\w+\$/gi, function(matchs) {
//matchs输出符合正则表达式"$\w+\$"的所有字符串,如$data$
//matchs.replace(/\$/g, "")就是将$替换为"",如$data$替换后为data
var returns = obj[matchs.replace(/\$/g, "")];
return (returns + "") == "undefined"? "": returns;
});
};
test = function(){
var jsonData_notice = {
//url: "/project/xxx.do?method=xxx",
data: [{
id: "11",
title:"通知1",
data:"2014/09/12"
},{
id: "12",
title:"通知2",
data:"2014/09/11"
},{
id: "13",
title:"通知3",
data:"2014/09/10"
}]
};
var jsonData_inside_news = {
//url: "/project/xxx.do?method=xxx",
data: [{
id: "21",
title:"国内新闻1",
data:"2014/09/12"
},{
id: "22",
title:"国内新闻2",
data:"2014/09/11"
},{
id: "23",
title:"国内新闻3",
data:"2014/09/10"
}]
};
var jsonData_outside_news = {
//url: "/project/xxx.do?method=xxx",
data: [{
id: "31",
title:"国外新闻1",
data:"2014/09/12"
},{
id: "32",
title:"国外新闻2",
data:"2014/09/11"
},{
id: "33",
title:"国外新闻3",
data:"2014/09/10"
}]
};
var htmlList_notice = "";
var htmlList_inside_news = "";
var htmlList_outside_news = "";
var htmlTemp = $("#notice").html();
var notice_temp = htmlTemp;
var inside_news_temp = htmlTemp;
var outside_news_temp = htmlTemp;
jsonData_notice.data.forEach(function(object) {
htmlList_notice += notice_temp.temp(object);
});
jsonData_inside_news.data.forEach(function(object) {
htmlList_inside_news += inside_news_temp.temp(object);
});
jsonData_outside_news.data.forEach(function(object) {
htmlList_outside_news += outside_news_temp.temp(object);
});
$("#notice").html(htmlList_notice);
$("#inside_news").html(htmlList_inside_news);
$("#outside_news").html(htmlList_outside_news);
};