表单排序问题

在这里插入图片描述

代码:

A.HTML
<input type="button" value="按年龄排序" id="btn1">
<input type="button" value="按姓名排序" id="btn2">
<div class="box" id="box"></div>
B.CSS
<style>
    table{
        border-collapse: collapse;
        width: 500px;
    }
    th{
        background: green;
        color: #fff;
    }
    td,th{
        border: 1px solid #333333;
    }
</style>
C.JavaScript
<script>
    var ary = [
        {name:'张三',age:18,sex:0,city:'北京'},
        {name:'李四',age:25,sex:1,city:'天津'},
        {name:'王五',age:22,sex:0,city:'廊坊'},
        {name:'赵六',age:30,sex:1,city:'上海'},
    ];
    var box = document.getElementById('box');
    function change() {
        var str = '<table><tr><th>姓名</th><th>年龄</th><th>性别</th><th>城市</th></tr>';
        for (var i=0;i<ary.length;i++){
            str += '<tr>';
            for (var key in ary[i]){
                if (key === 'sex'){
                    var temp = '';
                    temp = ary[i][key]===0 ? '男':'女';
                    str+='<td>'+temp+'</td>';
                }else{
                    str+='<td>'+ary[i][key]+'</td>';
                }
            }
            str+='</tr>'
        }
        str+='</table>';
        box.innerHTML = str;
    }
    //执行change方法,让数据显示在表格中(数据绑定)
    change();
    //当点击‘按年龄排序’按钮时,把数组按每个对象的age属性进行排序,并重新绑定数据
    document.getElementById('btn1').onclick = function () {
        ary.sort(function (a,b) {
            return a.age - b.age;
        });
        change();
    };
    //当点击‘按姓名排序’按钮时,把数组按每个对象的name属性进行排序,并重新绑定数据
    document.getElementById('btn2').onclick = function () {
       ary.sort(function (a,b) {
           return a.name.localeCompare(b.name,'zh');//指定语言
       });
       change();
    };
</script>

猜你喜欢

转载自blog.csdn.net/weixin_44675384/article/details/88919297