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
>
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
.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())
});
}
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
)
function showData(arr
){
if(arr
.length
<1){
return;
}
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>";
for(var attr
in arr
[i
]){
tableStr
+="<td>"+arr
[i
][attr
]+"</td>";
}
tableStr
+="</tr>"
}
table
.innerHTML
= tableStr
;
}
</script
>
转载请注明原文地址:https://tech.qufami.com/read-1103.html