主要在于修改js
1、获取新闻数据
2、定义模板
3、编译模板
4、定义事件过滤器
5、定义补零函数
使用模板引擎时,报template not found: Cannot read property ‘value‘ of null错误。
var sta = template('box', data)
第一个参数一定是script得id,不能是类
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<link rel="stylesheet" href="./assets/news.css" />
<script src="./lib/jquery.js"></script>
<script src="./lib/template-web.js"></script>
</head>
<body>
<div id="news-list">
</div>
<!-- 定义模板 -->
<script type="text/html" id="box">
{{each data}}
<!-- 因为有9条信息因此需要用循环 -->
<!-- 为什么是对data循环 -->
<div class="news-item">
<img class="thumb" src="{{'http://www.liulongbin.top:3006'+$value.img}}" alt="" />
<div class="right-box">
<h1 class="title">{{$value.title}}</h1>
<div class="tags">
{{each $value.tags}}<span>{{$value}}</span>{{/each}}
</div>
<div class="footer">
<div>
<span>{{$value.source}}</span>
<span>{{$value.time | dateFormat}}</span>
</div>
<span>评论数:{{$value.cmtcount}}</span>
</div>
</div>
</div>
{{/each}}
</script>
<script src="./js/06.js"></script>
</body>
</html>
window.onload = function() {
$(function() {
//定义补零函数,给时间
function pad(n) {
if (n < 10) {
return '0' + n
} else {
return n
}
}
template.defaults.imports.dateFormat = function(date) {
var dt = new Date(date)
var y = dt.getFullYear()
var m = pad(dt.getMonth() + 1)
var d = pad(dt.getDate())
var h = pad(dt.getHours())
var mm = pad(dt.getMinutes())
var ss = pad(dt.getSeconds()) //'y-m-d h:mm:ss'
return y + '-' + m + '-' + d + ' ' + h + ':' + mm + ':' + ss
}
function getlist() { //获取新闻列表的数据
$.ajax({
method: 'GET',
url: 'http://www.liulongbin.top:3006/api/news',
success: function(res) {
console.log(res);
if (res.status != 200) {
alert('获取数据失败')
} else {
//先对数据进行改造,将tags得字符串改成一个数组
for (var i = 0; i < res.data.length; i++) {
res.data[i].tags = res.data[i].tags.split(',')
}
var sta = template('box', res)
$('#news-list').html(sta)
// console.log(res.data); //服务器响应的数据
// $.each(res.data, function(i, data) {//不是这样对9条数据进行循环得
// console.log(data); //定义数据
// //调用模板函数
// var sta = template('box', data) //调用模板
// //渲染html结构
// console.log(sta);
// // <!-- 将数据填充到box里面 -->
// $('#news-list').html(sta)
// })
//怎么对数据进行循环渲染
}
}
})
}
getlist()
//定义模板
//定义时间过滤器
})
}
.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;
}