2016-12-02 134 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

    相關問題