日期:2014-05-16 浏览次数:20441 次
//初始状态 <a id="order" href="#">点击排序</a> <div id="list-tag"> <a href="#" title="1 个话题" >标签 No1</a> <a href="#" title="6 个话题" >标签 No2</a> <a href="#" title="3 个话题" >标签 No3</a> <a href="#" title="5 个话题" >标签 No4</a> <a href="#" title="10 个话题" >标签 No5</a> </div> //排序输出 <a id="order" href="#">点击排序</a> <div id="list-tag"> <a href="#" title="10 个话题" >标签 No5</a> <a href="#" title="6 个话题" >标签 No2</a> <a href="#" title="5 个话题" >标签 No4</a> <a href="#" title="3 个话题" >标签 No3</a> <a href="#" title="1 个话题" >标签 No1</a> </div>
<!DOCTYPE HTML> <html> <head> <meta charset="gb2312" /> <title></title> <style> a { display:inline-block; width:90px; } </style> </head> <body> <button id="asc">asc</button> <button id="desc">desc</button> <div id="list-tag"> <a href="#" title="1 个话题" >标签 No1</a> <a href="#" title="6 个话题" >标签 No2</a> <a href="#" title="3 个话题" >标签 No3</a> <a href="#" title="5 个话题" >标签 No4</a> <a href="#" title="10 个话题" >标签 No5</a> </div> <script> function $(o){return document.getElementById(o)} function makeArray( obj ){ var arr = []; for ( var i = 0, len = obj.length; i < len; i++ ){ arr.push(obj[i]); } return arr; } function asc( x, y ){ //升序 return parseInt( x.title.match(/\d+/) ) - parseInt( y.title.match(/\d+/) ); } function makeOrder( wrapper, obj, order ){ var order = order || 'asc'; var wrapper = $( wrapper ); var obj = wrapper.getElementsByTagName( obj ); var arr; arr = makeArray( obj ); // 将对象转为数组 if ( order == 'asc' ){ arr.sort( asc ); } else { arr.sort( asc ).reverse(); } for( var i = 0, len = arr.length; i < len; i++ ){ wrapper.appendChild( arr[i] ) } } $('desc').onclick = function(){ makeOrder( 'list-tag', 'a', 'desc' ) } $('asc').onclick = function(){ makeOrder( 'list-tag', 'a', 'asc' ) } </script> </body> </html>
------解决方案--------------------
jquery 直接sort就可以了
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <titl