注意:本项目主要利用到了template,模板引擎进行编写
模板引擎代码下载地址
<div id="news-list"><!-- 这里放数据 --></div>
.news-item {display: flex;border: 1px solid #eee;width: 700px;padding: 10px;margin-bottom: 5px;
}.thumb {display: block;width: 230px;height: 140px;background-color: #ccc;margin-right: 10px;
}.right-box {display: flex;flex-direction: column;justify-content: space-between;font-size: 12px;flex: 1;
}.title {font-size: 20px;font-weight: normal;
}.tags span {display: block;float: left;background-color: #F0F0F0;line-height: 20px;padding: 0 10px;border-radius: 10px;margin-right: 8px;
}.footer {display: flex;justify-content: space-between;
}
<script src="./lib/jquery.js"></script><script src="./lib/template-web.js"></script><!-- 定义模板 --><script type="text/html" id="newslist">{{each data val}}<div class="news-item"><img class="thumb" src="http://www.liulongbin.top:3006{{val.img}}" alt=""><div class="right-box"><h1 class="title">{{val.title}}</h1><div class="tags">{{each val.tags.split(',') v}}<span>{{v}}</span>{{/each}}</div><div class="footer"><div><span>{{val.source}}</span> <span>{{val.time|formatTime}}</span></div><span>评论数:{{val.cmtcount}}</span></div></div></div>{{/each}}</script>// 发送ajax请求。获取所有的新闻列表数据$.ajax({url: 'http://www.liulongbin.top:3006/api/news',success: function (res) {// console.log(res);// 调用template函数let str = template('newslist', res);$('#news-list').html(str);}});</script>
自定义获取系统时间函数
<script>// 过滤器函数,处理时间template.defaults.imports.formatTime = function (x) {// x 不是时间日期对象.因为服务器返回的只能是字符串,所以x是一个字符串格式的时间x = new Date(x);let year = x.getFullYear();let month = addZero(x.getMonth() + 1);let day = addZero(x.getDate());let hour = addZero(x.getHours());let minute = addZero(x.getMinutes());let second = addZero(x.getSeconds());return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;}// 定义补 0 函数function addZero (n) {return n < 10 ? '0' + n : n;}