我有一个数组[“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>
答案 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());
答案 1 :(得分:1)
这是你可以做到的一种方式,希望这会对你有所帮助
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;