首页 > 代码库 > javascript 排序li
javascript 排序li
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>New Web Project</title> <script> window.onload=function(){ var oU1=document.getElementById('uAge1'); var oU2=document.getElementById('uAge2'); var oBtn=document.getElementById('btn'); function sortNumber(l1,l2){ var n1=parseInt(l1.innerHTML); var n2=parseInt(l2.innerHTML); return n1-n2; } oBtn.onclick=function(){ var oLis=oU1.children; var oAry=[]; for(var j=0;j<oLis.length;j++) { oAry[j]=oLis[j]; } oAry.sort(sortNumber); for(var i=0;i<oLis.length;i++) { oU1.appendChild(oAry[i]); } }; }; </script> </head> <body> <ul id="uAge1"> <li>15</li> <li>66</li> <li>9</li> <li>10</li> <li>30</li> </ul> <input id="btn" type="button" value=http://www.mamicode.com/"排序" />>注意事项:
1.appendChild()调用时,会有两步操作
根据这两点,我们可以对元素集进行排序操作。
- 首先从父级元素中删除本元素
- 将此元素添加到调用这个函数的父级
2.oU1.children获得元素集合跟 oU1.getElementsByTagName()获得的集合是等价的
3. sort()排序操作,是Array类型的数组独有的操作函数,集合不能使用,所以需要将获得的集合转换成数组才可以调用这个函数
运行结果如下图:
javascript 排序li
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。