我有一个看起来像这样的列表:
<ul class="mylist">
<li>AAA</li>
<li>AAA</li>
<li>AAA</li>
<li>BBB</li>
<li>BBB</li>
<li>CCC</li>
</ul>
我现在想在内容组上方添加内容的第一个字母。
以下是结果的示例:
<ul class="mylist">
<li><strong>A</strong></li>
<li>AAA</li>
<li>AAA</li>
<li>AAA</li>
<li><strong>B</strong></li>
<li>BBB</li>
<li>BBB</li>
<li><strong>C</strong></li>
<li>CCC</li>
</ul>
我该怎么做?
答案 0 :(得分:1)
使用jQuery非常简单 - 请参阅代码注释以获得解释。
// shorthand for on document load
$(function() {
// a variable to store our current first letter
var currentFirstLetter;
// for every child of mylist
$('.mylist').children().each(function() {
// take the first character of its content
var thisLetter = $(this)[0].innerHTML.substr(0,1).toLowerCase();
// if its different to our current first letter then add the required element
// and update our current first letter
if (thisLetter !== currentFirstLetter) {
$(this).before("<li><strong>" + thisLetter.toUpperCase() + "</strong></li>");
currentFirstLetter = thisLetter;
}
});
});