将数组放入HTML表并升序或降序
我正在尝试在页面加载时将JavaScript数组放入HTML表格中,然后在单击箭头(向上或向下)时将其排列为升序或降序。
这是我的脚本:
var lakeData = [ { "Month": "1959-01", "LakeErieLevels": 12.296 }, { "Month": "1959-02", "LakeErieLevels": 13.131 }, { "Month": "1959-03", "LakeErieLevels": 13.966 }, { "Month": "1959-04", "LakeErieLevels": 15.028 }, { "Month": "1959-05", "LakeErieLevels": 15.844 }, { "Month": "1959-06", "LakeErieLevels": 15.769 }, { "Month": "1959-07", "LakeErieLevels": 15.237 }, { "Month": "1959-08", "LakeErieLevels": 14.801 }, { "Month": "1959-09", "LakeErieLevels": 14.137 }, { "Month": "1959-10", "LakeErieLevels": 13.89 }, { "Month": "1959-11", "LakeErieLevels": 13.416 }, { "Month": "1959-12", "LakeErieLevels": 13.871 }, { "Month": "1960-01", "LakeErieLevels": 14.478 }, { "Month": "1960-02", "LakeErieLevels": 14.725 }, { "Month": "1960-03", "LakeErieLevels": 14.763 }, { "Month": "1960-04", "LakeErieLevels": 15.806 }, { "Month": "1960-05", "LakeErieLevels": 16.565 }, { "Month": "1960-06", "LakeErieLevels": 17.097 }, { "Month": "1960-07", "LakeErieLevels": 17.306 }, { "Month": "1960-08", "LakeErieLevels": 17.211 }, { "Month": "1960-09", "LakeErieLevels": 16.717 }, { "Month": "1960-10", "LakeErieLevels": 15.787 }, { "Month": "1960-11", "LakeErieLevels": 14.801 }, { "Month": "1960-12", "LakeErieLevels": 14.231 } ];
这是我的一点点HTML:
Date Average Depth
我知道这似乎很简单,但我很难过。 同样,我正在尝试在页面加载时将数组加载到HTML表格中,然后当您单击向上箭头或向下箭头时,表格会按升序或降序排列。
排序数据
您可以使用数组Sort函数来升序和降序数据(对象数组),例如,
/** Sorting the data in asscending by comparing month **/ function inOrderAsc(a, b){ return a.Month == b.Month ? 0 : +(a.Month > b.Month) || -1; } /** Sorting the data in descending by comparing month **/ function inOrderDesc(a, b){ return a.Month == b.Month ? 0 : +(a.Month < b.Month) || -1; } function accending(objs){ return objs.sort(inOrderAsc); } function descending(objs){ return objs.sort(inOrderDesc); }
附上活动
附加按键事件,将执行排序操作,
/**Attach event, on which the sort action will be performed **/ document.onkeydown = initEvent; function initEvent(e) { e = e || window.event; if (e.keyCode == '38') { var result = accending(lakeData); displayData( result); } else if (e.keyCode == '40') { var result = descending(lakeData); displayData(result); } }
显示数据
现在最后在排序后显示数据,
/** Display the data in table **/ function displayData(objs){ var row, cell, cell2; var tbody = document.querySelector('#lake tbody'); var cloneTbody = tbody.cloneNode(false); tbody.parentNode.replaceChild(cloneTbody, tbody); for(var i=0; i
完整的演示在JsFiddle上 。