我有一个类似的问题,但我的情况是生成一个带有标题的图像列表来对项目进行分组。
我这样做是我知道的唯一方法,它确实有效,但我愿意接受有关如何做得更好的建议。
这是js代码:
var listItem, header,
dataList = document.getElementById('dataList');// this is my list already in the DOM
var list = [];
var user = localDB.getScreenName();
$.ajax({
url: reg.api(),
data: {action: 'getAttire', formData: user},
type: 'post',
dataType: 'jsonp',
jsonp: false,
jsonpCallback: 'result',
beforeSend: function() {
document.getElementById('indicator').style.display = 'block';
},
complete: function() {
document.getElementById('indicator').style.display = 'none';
},
success: function(res) {
//showbList();
var title = [];
for (var i = 0; i < res.length; i++) {
if ($.inArray(res[i].item, title) === -1) {
title.push(res[i].item);//creates header array with unique values cos i had headers with duplicate names
}
// This creates header Array from the list
}
for (var k = 0; k < title.length; k++) {
header = document.createElement('div');
header.setAttribute('data-bb-type', 'header');
header.id = 'headers';
header.innerHTML = title[k];
header.style.background = '#f6f6f6';
header.style.fontSize = '20px';
header.style.fontWeight = 'bold';
// header.style.boxShadow = ''
list.push(header);//header created here
for (var i = 0; i < res.length; i++) {
if (header.innerHTML === 'Bag' && res[i].item === 'Bag') {
//var date =
listItem = document.createElement('div');
listItem.setAttribute('data-bb-type', 'item');
listItem.setAttribute('data-bb-img', res[i].img_link);
listItem.setAttribute('data-bb-title', res[i].name);
listItem.setAttribute('data-bb-accent-text', 'Added: '+jQuery.timeago(res[i].date));
listItem.setAttribute('dressup',res[i].DRESS_ID);
listItem.setAttribute('id','wardropeLink');
listItem.innerHTML = "Suited for: " + res[i].suited;
listItem.style.color = "#fff";
listItem.onclick = function() {
var selected = document.getElementById('wardropeLink').getTitle();
console.log(selected); // trying to get d title of a selected or clicked list but it returns the whole group. still working on it
};
list.push(listItem); //list item for a particular header created here
}
if (header.innerHTML === 'Trousers' && res[i].item === 'Trousers') {
listItem = document.createElement('div');
listItem.setAttribute('data-bb-type', 'item');
listItem.setAttribute('data-bb-img', res[i].img_link);
listItem.setAttribute('data-bb-title', res[i].name);
listItem.setAttribute('data-bb-accent-text', jQuery.timeago(res[i].date));
listItem.innerHTML = "Suited for: " + res[i].suited;
listItem.style.color = "#fff";
listItem.onclick = function() {
handleWardrope.listItems(res[i].DRESS_ID);
};
list.push(listItem);
}
}
}
var items = dataList.getItems();
if (items.length > 0) {
//list.insertItemBefore(item, items[0]);
} else {
dataList.refresh(list);//list added to DOM
if (bb.scroller) {
bb.scroller.refresh();
}
}
}
});
return false;
希望这可以帮助。
警告并且仍在尝试使 onclick 功能适用于特定列表项,但它似乎将它们分组为循环的 cos。