我试图按字母顺序在3列中显示多维数组,我能够对数组进行排序。
目前我的列表显示为:
Amanda Brad Lisha Madley Mowaki
但是,我希望结果如下格式
Amanda Lisha Mowaki Brad Madley
这是我的Fiddle
HTML:
<div>
<div class='main'></div>
<div id='description'></div>
</div>
JS:
$(function () {
function compare(a, b) {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
}
data.sort(compare);
for (var i = 0; i < data.length; i++) {
var dataItem = "<a href='#' class='dataItem' data-description='" + data[i].desc + "'>" + data[i].name + " <strong>(" + data[i].age + ")</strong>" + "</a>";
$('.main').append(dataItem);
//alert(data[i]['name']);
if (i % 3 == 2) {
$('.main').append("</br>");
}
}
var description = $('#description');
$('a.dataItem').on('click', function (e) {
description.text($(this).data('description'));
})
});
感谢。
答案 0 :(得分:0)
首先将数据项附加到列div然后将列添加到main,然后将div向左浮动
CSS
.column {
float:left; //Put each column next to each other.
}
.column .dataItem {
display:block; //so each one displays on its own line.
}
的Javascript
var column = jQuery('<div class="column"></div>');
var maxColumnRows = 2;
var rIndex = 0;
for(var i=0;i<data.length;i++)
{
if(rIndex > maxColumnRows-1) { //-1 because 0 index
$('.main').append(column);
column = jQuery('<div class="column"></div>');
rIndex=0;
}
var dataItem = "<a href='#' class='dataItem' data-description='" + data[i].desc + "'>" + data[i].name + " <strong>(" + data[i].age + ")</strong>" + "</a>";
column.append(dataItem);
rIndex++;
}
$('main').append(column); //append last column
答案 1 :(得分:0)
您的数组似乎正在正确排序,它只是包装到该div的第二行。这里的问题不是排序,而是html布局。
在排序数组后,您需要做的事情如下:
首先创建三个html列。使用css float:left; width: 33%;
将它们彼此相邻。然后,您需要计算将多少条数据分成三列,然后将它们以块的形式放入列中。有一些数学,但它并不太疯狂。
HTML:
<div id="col-A"></div>
<div id="col-B"></div>
<div id="col-C"></div>
的Javascript
var cols = 3;
var data = [/*This is your array*/];
//find out how many things we should have for three equal columns
var numPerCol = Math.ceil(data.length/cols);
//this lets us reference column names by number (0,1,2)
var colNames = ["col-A","col-B","col-C"];
var whichCol, colElem, newElem;
//loop through the data!
for( var i=0; i<cols; i++){
//determine which column this piece of data is going in 0 = col-A, 1 = col-B etc
whichCol = Math.floor(i/numPerCol);
//retrieve the column element
colElem = document.getElementById(colNames[whichCol]);
//create a new div element for our piece of data
newElem = document.createElement("div");
newElem.innerText = data[i];
newElem.style.display = "block";
//slap it into the column!
colElem.appendChild(newElem);
}
以下是这项工作的小提琴,我相信您可以修改它以适合您的数据:http://jsfiddle.net/hbQ2T/
它足够动态,无论您拥有多少数据,它都会将它分成三列。