<!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.οnlοad=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.οnclick=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="排序" />
</body>
</html>
注意事项:
1.appendChild()调用时,会有两步操作
- 首先从父级元素中删除本元素
- 将此元素添加到调用这个函数的父级
2.oU1.children获得元素集合跟 oU1.getElementsByTagName()获得的集合是等价的
3. sort()排序操作,是Array类型的数组独有的操作函数,集合不能使用,所以需要将获得的集合转换成数组才可以调用这个函数
运行结果如下图: