模板字符串
使用模板引擎可以帮助我们更加快速的渲染页面,需要引入第三方的js文件来使用,习惯了语法还是很方便的。
- 常见的模板引擎 ?
=> art-template, 前后端都可以用
=> underscroll, 后端 JS 不能用
=> e.js, 后端 JS 不能用
=> template, 后端 JS 不能用 - 使用步骤
①先导入第三方JS文件
<script src="./lib/template-web.js"></script>
②建立type为text/html的script标签,设置一个id方便调用。
<script type="text/html" id="tmp">
{{each list}}
<div class="xiaoji">
¥{{ $value.goods_price * $value.cart_number }}
</div>
</li>
{{ /each }}
</script>
③用template方法调用
var str = template('tmp', {
list: cart,
total: total,
totalPrice: totalPrice.toFixed(2)
})
box.innerHTML = str
捕获数据
var listbox = document.querySelector('.listbox')
var viewPortHeight = document.documentElement.clientHeight
var uloffsetTop = listbox.offsetTop
var totalPage = Math.ceil(data.length / 20)
var currentPage = 1
var flag = true
var loading = document.querySelector('.loading')
渲染数据 ->bindHTML()
function bindHTML() {
var bindList = data.slice((currentPage - 1) * 20, currentPage * 20)
var frg = document.createDocumentFragment()
bindList.forEach(element => {
var li = document.createElement('li')
li.innerHTML = `
<div class="img">
<img src="${ element.goods_big_logo}" alt="">
</div>
<p>${ element.goods_name}</p>
<span>¥${ element.goods_price.toFixed(2).big().fontcolor('red')}</span>
`
var btn = document.createElement('button')
btn.innerHTML = '添加到购物车'
btn.setAttribute('goodsid', element.goods_id)
btn.onclick = addCart
li.appendChild(btn)
frg.appendChild(li)
});
listbox.appendChild(frg)
flag = true
loading.classList.remove('active')
}
bindHTML()
下拉刷新 ->window.oncroll = function(){}
window.onscroll = function () {
var scrollTop = (document.documentElement.scrollTop || document.body.scrollTop) + viewPortHeight
var ulHeight = uloffsetTop + listbox.offsetHeight
// console.log('scrollTop'+ scrollTop)
// console.log("ulHeight" + ulHeight)
if (scrollTop < ulHeight) return
if (currentPage === totalPage) return
if (!flag) return //开关为开 就跳过去继续执行
flag = false //为了保证只执行一次 接着关掉开关
loading.classList.add('active')
setTimeout(function () {
currentPage++
bindHTML()
}, 1000)
}
添加商品到购物车 ->addCart()
function addCart(){
var goodsid = this.getAttribute('goodsid')-0
var goods = data.find(function(item){return item.goods_id === goodsid})
var list = JSON.parse(window.localStorage.getItem('cart')) || []
if(!list.length){ //if list is empty ,
goods.cart_number = 1
list.push(goods)
}else{
var res = list.some(function(item){return item.goods_id === goodsid})
if(res){
var index = list.findIndex(function (item) { return item.goods_id === goodsid })
list[index].cart_number++
// goods.cart_number++
// console.log(list[index].cart_number)
// console.log(goods.cart_number)
}else{
goods.cart_number = 1
list.push(goods)
}
}
window.localStorage.setItem('cart',JSON.stringify(list))
}