<!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 class="news-item">
<img class="thumb" src="" alt="" />
<div class="right-box">
<h1 class="title">5G商用在即,三大运营商营收持续下降</h1>
<div class="tags">
<span>三大运营商</span>
<span>中国移动</span>
<span>5G商用</span>
</div>
<div class="footer">
<div>
<span>胡润百富</span>
<span>2019-10-28 10:14:38</span>
</div>
<span>评论数:66</span>
</div>
</div>
</div>
</div>
</body>
</html>
.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;
}
请求的根路径
代码
$(function () {
function getNewsList() {
$.get('http://www.liulongbin.top:3006/api/news', function (res) {
console.log(res);
})
}
getNewsList()
})
<script type="text/html">
<div class="news-item">
<img class="thumb" src="" alt="" />
<div class="right-box">
<h1 class="title">5G商用在即,三大运营商营收持续下降</h1>
<div class="tags">
<span>三大运营商</span>
<span>中国移动</span>
<span>5G商用</span>
</div>
<div class="footer">
<div>
<span>胡润百富</span>
<span>2019-10-28 10:14:38</span>
</div>
<span>评论数:66</span>
</div>
</div>
</div>
</script>
将html页面中的新闻item div剪切放到script标签里面。
//将每项tags转换成数组 便于循环使用。
for (let index = 0; index < res.data.length; index++) {
res.data[index].tags = res.data[index].tags.split(',');
}
//调用输出
let str = template('tpl-news', res);
$('#news-list').html(str);
})
//定义过滤器
template.defaults.imports.dateFormat = function (dtstr) {
//补零
function a(n) {
return n = n < 10 ? '0' + n : n;
}
let dt = new Date(dtstr)
let Y = dt.getFullYear();
let M = a(dt.getMonth() + 1);
let D = a(dt.getDate());
let hh = a(dt.getHours());
let mm = a(dt.getMinutes());
let ss = a(dt.getSeconds());
return Y + '-' + M + '-' + D + " " + hh + ':' + mm + ':' + ss;
}
<span>{{$value.time | dateFormat}}</span>