如何将数组转换为<ul> <li>以字母为标题的字母顺序列表</li> </ul>

时间:2015-03-19 01:59:51

标签: javascript jquery intel-xdk appframework

我有一个数组[“Apple”,“Orange”,“Pineapple”]

如何将其转换为以下列表。

<ul>

<li id = "header">A</li>
<li id = "list" >Apple</li>

<li id = "header">O</li>
<li id = "list" >Orange</li>

<li id = "header">P</li>
<li id = "list" >Pineapple</li>

</ul>

2 个答案:

答案 0 :(得分:2)

var array = ["Apple", "Another-fruit", "Orange", "Pineapple"];

function createList() {
    var list = document.createElement("ul");
    var listItem;
    var currentLetter = '';

    for (var i = 0, length = array.length; i < length; i++) {
        var item = array[i];
        var firstLetter = item.charAt(0);

        if (currentLetter != firstLetter) {
            currentLetter = firstLetter;

            listItem = document.createElement("li");
            listItem.innerHTML = firstLetter;

            list.appendChild(listItem);
        }

        listItem = document.createElement("li");
        listItem.innerHTML = item;

        list.appendChild(listItem);
    }

    return list;
}

document.body.appendChild(createList());

http://jsfiddle.net/bvaughn/edyLg9ga/4/

答案 1 :(得分:1)

这是你可以做到的一种方式,希望这会对你有所帮助

&#13;
&#13;
var arr = ["Apple", "Orange", "Pineapple"];
var $el = '<ul>';
$.each(arr, function(i, v) {
  $el += '<li id = "header">' + v.slice(0, 1) + '</li>';
  $el += '<li id = "list" >' + v + '</li>';
});
$el += '<ul>';
$('body').append($el);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;