带标题按字母顺序排列HTML列表 [英] Alphabetically Order HTML List with Headers
问题描述
我希望按字母顺序排列HTML列表,但是在每个字母之后,将有一个<hr />
标记和一个标头,指示新的字母列表.
I am looking to Alphabetically order an HTML list, but after each letter, there would be a <hr />
tag and a header, indicating the new letter list.
要修改一下(如果我不够清楚的话),我有清单...
To revise if I wasn't clear enough, I have my list...
<ul>
<li><a href="#/"> john-smith/</a></li>
<li><a href="#/"> joe-smith/</a></li>
<li><a href="#/"> glen-smith/</a></li>
<li><a href="#/"> daniel-smith/</a></li>
<li><a href="#/"> johnny-smith/</a></li>
</ul>
现在,我希望有一些JS代码可以按字母顺序组织此列表,并提供标题&每个新字母的行;因此它会产生类似于以下内容的结果:
And now, I wanted to have some JS code that would organise this list alphabetically, as well as give a header & line for each new letter; thus it would give an outcome somewhat similar to:
<ul>
<hr />
<h3>D</h3>
<li><a href="#/"> daniel-smith/</a></li>
<hr />
<h3>G</h3>
<li><a href="#/"> glen-smith/</a></li>
<hr />
<h3>J</h3>
<li><a href="#/"> joe-smith/</a></li>
<li><a href="#/"> johnny-smith/</a></li>
<li><a href="#/"> joe-smith/</a></li>
</ul>
我确实尝试过自己做,但是我根本做不到,因为我对JavaScript还是比较陌生! 谢谢.
I did try to do this myself, but I simply wasn't able to, I'm relatively new to JavaScript! Thanks.
推荐答案
由于您不能将h3
和hr
放在ul
标记中,因此我使用CSS创建了此样式.刚刚添加了带有splitter
类的li
节点.
Due you can't put h3
and hr
in ul
tag, I created this style with css. Just added a li
node with splitter
class.
您有2个步骤:
- 对列表进行排序(使用
.sort()
方法) - 创建标题.
阅读代码,让我知道是否不清楚.
Read the code and let me know if something not clear.
var list = $('ul'),
items = $('li', list);
// sort the list
var sortedItems = items.get().sort(function(a, b) {
var aText = $.trim($(a).text().toUpperCase()),
bText = $.trim($(b).text().toUpperCase());
return aText.localeCompare(bText);
});
list.append(sortedItems);
// create the titles
var lastLetter = '';
list.find('li').each(function() {
var $this = $(this),
text = $.trim($this.text()),
firstLetter = text[0];
if (firstLetter != lastLetter) {
$this.before('<li class="splitter">' + firstLetter);
lastLetter = firstLetter;
}
});
.splitter {
border-top: 1px solid;
font-size: 1.25em;
list-style: none;
padding-top: 10px;
text-transform: uppercase;
padding-bottom: 10px;
margin-top: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a href="#/"> john-smith/</a></li>
<li><a href="#/"> joe-smith/</a></li>
<li><a href="#/"> glen-smith/</a></li>
<li><a href="#/"> daniel-smith/</a></li>
<li><a href="#/"> johnny-smith/</a></li>
</ul>
这篇关于带标题按字母顺序排列HTML列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!