我想按字母顺序对带有链接的列表进行排序,这是我的代码:
!DOCTYPE html>
<html>
<head>
<title>Sort list items alphabetically with Javascript</title>
<script type="text/javascript">
function sortUnorderedList(ul, sortDescending) {
if(typeof ul == "string")
ul = document.getElementById(ul);
var lis = ul.getElementsByTagName("LI");
var vals = [];
for(var i = 0, l = lis.length; i < l; i++)
vals.push(lis[i].innerHTML);
vals.sort();
if(sortDescending)
vals.reverse();
for(var i = 0, l = lis.length; i < l; i++)
lis[i].innerHTML = vals[i];
}
window.onload = function() {
var desc = false;
document.getElementById("test").onclick = function() {
sortUnorderedList("list", desc);
desc = !desc;
return false;
}
}
</script>
</head>
<body>
<div id="test"> <a href="#">Sort List</a></div>
<ul id="list">
<li>Peter</li>
<li>Mary</li>
<li>Paul</li>
<li>Allen</li>
<li>James</li>
<li>Vicki</li>
<li>Brock</li>
<li>Dana</li>
<li>Frank</li>
<li>Gil</li>
<li>Helen</li>
</ul>
</body>
但是,当我想为名称添加链接时,列表变得一团糟(不再按字母顺序排列),那么我应该改变什么?我完全不了解javascript,有人可以在这里帮助我吗,谢谢
<div id="test"> <a href="#">Sort List</a></div>
<ul id="list">
<li><a href="tumblr.com/post/57781372261">Peter</a></li>
<li><a href="tumblr.com/post/57783141055">Mary</a></li>
<li><a href="tumblr.com/post/57781372261">Paul</a></li>
</ul>
添加链接后,帖子将按那里的数字排序,而不是按名称排序。