Playing with a quick concept. Hopefully the answer is pretty simple, my attempt is just failing here for some reason.
Let's say I have an array such as:
var items = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]];
And I'm trying to flip the data around, so it converts it into:
var items_converted = [[1,4,7,10],[2,5,8,11],[3,6,9,12]];
This much is completed. Now, with my new multidimensional array, I want to push each internal array's contents to an HTML table row:
<tr>
<td>1</td>
<td>4</td>
<td>7</td>
<td>10</td>
</tr>
<tr>
<td>...
I tried doing it with two for-loops
, but it doesn't seem to be appending the <tr>
or </tr>
.
var items = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]];
var items_converted = [[1,4,7,10],[2,5,8,11],[3,6,9,12]];
var table = $('#table');
for(var i=0; i<items_converted.length; i++){
if(i==0){
table.append('<tr>');
}
for(var j=0; j<items_converted[i].length; j++){
table.append('<td>'+items_converted[i][j]+'</td>');
if(j===items_converted[0].length-1){
table.append('</tr');
}
}
}
I feel I'm missing something very simple here... perhaps the order that the loops are processing?
Any help is appreciated.
You're trying to use append()
like document.write()
. That's a wrong approach. You should look at the DOM starting at your table
node and append nodes for each row and cell.
Basically a $('<tr>')
to create a row, followed by an table.append()
call to add it to the DOM. Likewise for the cells.
var items = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]];
var items_converted = [[1,4,7,10],[2,5,8,11],[3,6,9,12]];
var table = $('#table');
var row, cell;
for(var i=0; i<items_converted.length; i++){
row = $( '<tr />' );
table.append( row );
for(var j=0; j<items_converted[i].length; j++){
cell = $('<td>'+items_converted[i][j]+'</td>')
row.append( cell );
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.