JavaScript 综合练习 4
1. 案例演示
2. 代码实现
<! DOCTYPE html >
< html lang = " en" >
< head>
< meta charset = " UTF-8" />
< meta name = " viewport" content = " width=device-width, initial-scale=1.0" />
< title> js综合案例4</ title>
</ head>
< body>
< button id = " like" > 通过好评排序</ button>
< button id = " price" > 通过价格排序</ button>
< ul id = " list" > </ ul>
< script>
const sales = [
{
name : "张三" ,
like : 30 ,
price : 100 ,
} ,
{
name : "李四" ,
like : 60 ,
price : 66 ,
} ,
{
name : "王五" ,
like : 10 ,
price : 102 ,
} ,
] ;
const list = document. getElementById ( "list" ) ;
const like = document. getElementById ( "like" ) ;
const price = document. getElementById ( "price" ) ;
const removeLis = ( ) => {
const lis = document. querySelectorAll ( "li" ) ;
console. log ( lis) ;
lis. forEach ( ( li ) => {
list. removeChild ( li) ;
} ) ;
} ;
const reRenderList = ( array ) => {
removeLis ( ) ;
array. forEach ( ( sale ) => {
const li = document. createElement ( "li" ) ;
li. innerHTML = ` ${ sale. name} ----- ${ sale. like} ----- ${ sale. price} ` ;
list. appendChild ( li) ;
} ) ;
} ;
const ordered = ( array, attr ) => {
return array. sort ( ( a, b ) => {
return a[ attr] - b[ attr] ;
} ) ;
} ;
reRenderList ( sales) ;
like. onclick = ( ) => {
const result = ordered ( sales, "like" ) ;
reRenderList ( result) ;
} ;
price. onclick = ( ) => {
const result = ordered ( sales, "price" ) ;
reRenderList ( result) ;
} ;
</ script>
</ body>
</ html>