标签:uri 原来 content 绑定 排序 pre 其他 time wan
运用所学的知识做了一个商城排序的案例,实现了以下需求:
<div class="content">
<div class="header">
<span>排序</span>
<a href="javascript:;">上架时间
<i class="up"></i>
<i class="down"></i>
</a>
<a href="javascript:;">热度
<i class="up"></i>
<i class="down"></i>
</a>
<a href="javascript:;">价格
<i class="up"></i>
<i class="down"></i>
</a>
</div>
<ul id="list">
<li>
<img src="img/1.jpg" >
<span>华为畅享7(香槟金)</span>
<span>2018-01-01</span>
<span>1</span>
<span>992</span>
</li>
</ul>
</div>
<script>
var list = document.getElementById("list");
var oLi = list.getElementsByTagName("li");
var oHeader = document.getElementsByClassName("header")[0];
var oLinks = oHeader.getElementsByTagName("a");
//获取json数据
var goodsList = null;
var xhr = new XMLHttpRequest();//创建ajax实例
xhr.open("get", "./json/product.json", false);//获取请求(请求方式,请求的api,设置同异步)
//监听xhr的readyState状态的change事件
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
goodsList = xhr.responseText;
}
};
xhr.send(null);
goodsList = JSON.parse(goodsList);//将json字符转换为json对象。
//绑定数据
var str = "";
for (var i = 0; i < goodsList.length; i++) {
var goods = goodsList[i];
//es6模板字符串
str += `<li data-price="${goods.price}" data-hot="${goods.hot}" data-time="${goods.time}">
<img src="${goods.img}" >
<span>${goods.title}</span>
<span>上架时间:${goods.time}</span>
<span>热度:${goods.hot}</span>
<span>价格:¥${goods.price}</span>
</li>`
}
list.innerHTML = str;
//绑定点击事件
for (var i = 0; i < oLinks.length; i++) {
oLinks[i].index = i;
oLinks[i].flag = -1;
oLinks[i].onclick = function () {
for (var k = 0; k < oLinks.length; k++) {
if (oLinks[k]!==this){
oLinks[k].flag=-1; // 恢复标志的默认-1
}
}
var oIs1 = oHeader.getElementsByTagName("i");
for (var j = 0; j < oIs1.length; j++) {
oIs1[j].classList.remove("bg")
}
var oIs = this.getElementsByTagName("i");
if (this.flag == -1) {
oIs[0].classList.add("bg");
oIs[1].classList.remove("bg");
} else {
oIs[1].classList.add("bg");
oIs[0].classList.remove("bg");
}
this.flag *= -1;
mySort.call(this);
}
}
//排序
function mySort() {
var newLi = [].slice.call(oLi);// 获取完不是一个数组,需要转换成数组,然后在排序
var flag = this.flag;
var index = this.index;
newLi.sort(function (a, b) {
var aTtr, bTtr;
if (index == 0) {
aTtr = a.getAttribute("data-time").replace(/-/g, "");
bTtr = b.getAttribute("data-time").replace(/-/g, "");
} else if (index == 1) {
aTtr = a.getAttribute("data-hot");
bTtr = b.getAttribute("data-hot");
} else {
aTtr = a.getAttribute("data-price");
bTtr = b.getAttribute("data-price");
}
return (aTtr - bTtr) * flag;
});
for (var i = 0; i < newLi.length; i++) {
list.appendChild(newLi[i]);
}
}
</script>
标签:uri 原来 content 绑定 排序 pre 其他 time wan
原文地址:https://www.cnblogs.com/wangxingren/p/10225912.html