HTML案例——sort应用

tech2022-07-30  146

HTML代码

<div class="box"> <form> <p>姓名:<input type="text" id="xingming"></p> <p>身高:<input type="text" id="height"> cm</p> <p>体重:<input type="text" id="weight"> kg</p> <p>分数:<input type="text" id="score"></p> <p class="btn"><input type="button" value="提交信息" id="tijiao"></p> <p class="btn"><input type="button" value="身高排序" id="heightBtn"></p> <p class="btn"><input type="button" value="体重排序" id="weightBtn"></p> <p class="btn"><input type="button" value="分数排序" id="scoreBtn"></p> </form> <table id="table" > </table> </div>

CSS代码

<style> *{ margin: 0; padding: 0; } .box{ width: 500px; overflow: hidden; padding:10px; margin:20px auto; background:#f1f1f1; } p{ line-height: 40px; height: 40px; } input{ line-height: 25px; height: 25px; margin:7px 5px; padding:0 10px; outline:none; } [type='button']{ width: 100px; height: 25px; background:yellowgreen; border:none; border-radius: 10px; } .btn{ text-align: center; float: left; margin:5px 5px; } table{ display:none; } </style>

JS代码

<script> /* 需求分析: 1 收集班级学生信息(身高,体重,分数,姓名) 2 把收集到的班级学生信息,每人放一个对象里面,所有的对象放在一个数组里 3 点击按钮(身高,体重,分数)排序可以对班级学员进行排序 */ //相关id:姓名(xingming) 身高(height) 体重(weight) 分数(score) 提交信息(tijiao) 身高排序(heightBtn) 体重排序(weightBtn) 分数排序(scoreBtn) 表格(table) // 获取相关元素 function $id(id){ return document.getElementById(id); } $id("xingming"); $id("height"); $id("weight"); $id("score"); $id("tijiao"); $id("heightBtn"); $id("weightBtn"); $id("scoreBtn"); $id("table"); // 准备一个数组,存放学生数据 var studentArr = []; // 步骤一:给tijiao按钮添加点击事件 tijiao.onclick = function(){ // 点击以后把表单里面的数据放入一个对象,然后把对象放到数组中 studentArr.push({ name:$id("xingming").value.trim(), score:parseFloat($id("score").value.trim()), height:parseFloat($id("height").value.trim()), weight:parseFloat($id("weight").value.trim()) }); // console.log(studentArr); //插入数据没有问题 } // 步骤二:排序:降序 // 身高排序 heightBtn.onclick = function(){ //要对数组排序 studentArr.sort(function(a,b){ return b.height-a.height; //降序 }); showData(studentArr); } // 体重排序 weightBtn.onclick = function(){ //要对数组排序 studentArr.sort(function(a,b){ return b.weight-a.weight; //降序 }); showData(studentArr); } // 分数排序 scoreBtn.onclick = function(){ //要对数组排序 studentArr.sort(function(a,b){ return b.score-a.score; //降序 }); showData(studentArr); } console.log(studentArr) // 书写一个函数,根据你出入的数组,拼接成html字符串 function showData(arr){ if(arr.length<1){ return; } //把表格的display转换为block table.style.display = "block"; //生成表头 var tableStr = "<tr>"; //遍历第一次 for(var key in arr[0]){ tableStr+="<th>"+key+"</th>"; } tableStr+="</tr>"; //生成表格内容,有几个对象循环几次 for(var i=0;i<arr.length;i++){ tableStr+="<tr>"; //arr[i]是数组里面的对象,对象里面有几个对象就有几个td for(var attr in arr[i]){ tableStr+="<td>"+arr[i][attr]+"</td>"; } tableStr+="</tr>" } table.innerHTML = tableStr; } </script>
最新回复(0)