table cells not being rendered within it's table row
JSON Structure:
{"rows": [
{"row":[ {"cells": [ {"data": "Edit"}, {"data": "030194"}, ]} ]}, {"row":[ {"cells": [ {"data": "Add"}, {"data": "030194"}, ]} ]}, {"row":[ {"cells": [ {"data": "Delete"}, {"data": "030194"}, ]} ]}
]}
JQuery code:
$.each(response.rows, function(index, rows){
$.each(rows.row, function(index,row){ var element=$("tbody").append("<tr id='" + index + "'>"); var element1=element.append("<td><input type='checkbox'></input></td>"); 开发者_JS百科 $.each(this.cells, function(index){ element1.append("<td>" + this.data + "</td>"); }); $("tbody").append("</tr>"); });
});
Problems:
Each row generated has an ID with value of index = 0. The ID for Row1 should be 0, for Row2 it should be 1 and for Row3 ID should be equal to 2
td elements are drawn out as children of tbody. They should be children of tr
closing tr should be drawn after the last cell in each row, currently the tr closes itself before any cell is drawn
Try this. This stumped me for a bit, because I was used to the syntax of .each() in the context of looping through DOM elements. Since it's $.each(), the index of the first loop refers to the number you were trying to get for every row.
I moved the TR append outside the loop you had it in.
(Last-child isn't the fastest method of adding the TDs, you could use createElement like Endophage posted, and then refer to that)
http://jsfiddle.net/EY4an/
$.each(response.rows, function(index, rows) {
$("tbody").append('<tr id="index' + index + '"></tr>');
$.each(this.row, function(index) {
var element1 = $("tbody tr:last-child").append("<td><input type='checkbox'></input></td>");
$.each(this.cells, function(index) {
element1.append("<td>" + this.data + "</td>");
});
});
});
I also added the word 'index' to the ID attributes on the table rows, because IDs are supposed to start with a letter.
Not 100% certain about the index problem, but in terms of the rendering, here's a break down:
var element=$("tbody").append("<tr id='" + index + "'>");
I think this is where your mistake starts, at the above line, element will equal the tbody
, not the tr
.
var element1=element.append("<td><input type='checkbox'></input></td>");
Here you're now appending the td to the tbody
and then element1 will also equal the tbody
. , hence why the next append inside the each doesn't work correctly. Finally, you should only append whole elements, so appending the <tr>
and </tr>
as two separate operations should never be expected to work.
Try the below:
var row = document.createElement('tr');
row.setAttribute('id', index);
$("tbody").append(row);
$(row).append("<td><input type='checkbox'></input></td>");
$.each(this.cells, function(index){
$(row).append("<td>" + this.data + "</td>");
});
$("tbody").append(row);
Just a thought on the index problem. You're using the name index
twice. Try using a different variable name for one of them.
精彩评论