<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<button class='up'>销量升序</button>
<button class='down'>销量降序</button>
<ul></ul>
<script>
var cups = [
{ type: 1, price: 100, color: 'black', sales: 3000, name: '牛客logo马克杯' },
{ type: 2, price: 40, color: 'blue', sales: 1000, name: '无盖星空杯' },
{ type: 4, price: 60, color: 'green', sales: 200, name: '老式茶杯' },
{ type: 3, price: 50, color: 'green', sales: 600, name: '欧式印花杯' }
]
var ul = document.querySelector('ul');
var upbtn = document.querySelector('.up');
var downbtn = document.querySelector('.down');
// 补全代码
for(let i =0;i<cups.length;i++){
let li=document.createElement('li')
li.innerHTML=cups[i].name
ul.append(li)
}
var lis=document.querySelectorAll('li')
upbtn.onclick=function (){
cups.sort((a,b)=>a.sales-b.sales)
for (let i = 0; i < cups.length; i++) {
lis[i].innerHTML = cups[i].name;
}
}
downbtn.onclick=function (){
cups.sort((a,b)=>b.sales-a.sales)
for (let i = 0; i < cups.length; i++) {
lis[i].innerHTML = cups[i].name;
}
}
</script>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<button class='up'>销量升序</button>
<button class='down'>销量降序</button>
<ul></ul>
<script>
var cups = [
{ type: 1, price: 100, color: 'black', sales: 3000, name: '牛客logo马克杯' },
{ type: 2, price: 40, color: 'blue', sales: 1000, name: '无盖星空杯' },
{ type: 4, price: 60, color: 'green', sales: 200, name: '老式茶杯' },
{ type: 3, price: 50, color: 'green', sales: 600, name: '欧式印花杯' }
]
var ul = document.querySelector('ul');
var upbtn = document.querySelector('.up');
var downbtn = document.querySelector('.down');
// 补全代码
for(let i =0;i<cups.length;i++){
let li=document.createElement('li')
li.innerHTML=cups[i].name
ul.append(li)
}
var lis=document.querySelectorAll('li')
upbtn.onclick=function (){
cups.sort((a,b)=>a.sales-b.sales)
for (let i = 0; i < cups.length; i++) {
lis[i].innerHTML = cups[i].name;
}
}
downbtn.onclick=function (){
cups.sort((a,b)=>b.sales-a.sales)
for (let i = 0; i < cups.length; i++) {
lis[i].innerHTML = cups[i].name;
}
}
</script>
</body>
</html>