2016-12-02 135 views
-5

上面我有一个列表,它看起来有点像这样:选择的第一个字母,并把它的内容组

<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

请使用谷歌“如何遍历在UL的jQuery礼”,这将在这里得到你:https://api.jquery.com/each/那么你需要做的实现或尝试并在此发布。这不仅仅是可行的,你的问题最终应该是“这是行不通的”或者“我怎么能让这个算法更快?” – abc123

+0

您正在寻找JS/JQ包装器。您可以执行@ abc123建议并查看的在线资源,为此确切问题提供大量资源。一旦你理解了这个概念,你可以将代码放在一个插件或函数中,并且只需要在你想要包装的表上调用它。话虽如此,如果您已经尝试了几种方法并且无法解决问题,那么我们都可以更加有效地诊断这个问题 – Turk

回答

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; 
    } 
    }); 
}); 

jsFiddle

+0

谢谢,这种方法工作正常,但对大小写不敏感。所以如果你想添加'

  • aAA
  • ',它会添加另一个** a **。 – Reza

    +0

    你可以使用toLowerCase和toUpperCase方法操纵字符串 –

    +0

    哦哇......这是完美的!非常感谢你!你救了我的一天! :) – Reza

    相关问题