build html table with jQuery xml response
I'm attempting to iterate through a response from a jQuery Ajax request (returned as XML).
With that response, I'm building an HTML table with 3 columns (capable of an unlimited number of rows). Once the 4th XML node/ "company" is found, it should start a new row in the table. Any help with the JS to determine when the new row should be added is most appreciated. Thanks!
JS example:
/* jQuery Ajax Call here */
success: function(xml){
var trow = $("<tr>");
$(xml).find("Company").each(function(index){
var cellData = "<td width=\"33%\" valign=\"top\" ><div class=\"container\">"+
"<div class=\"item\"><a href=\"#\" title=\"\" target=\"\">"+ $(this).attr("Name")+ "</a></div>"+
"<div class=\"description\">"+ $(this).attr("Description") + "</div></div></div></td>";
$(cellData).appendTo(trow);
});
trow.appendTo('#tbl');
}
});
});
Example XML response from web service:
<Companies>
<Company ID="6" Name="Company name 1" Description="Lorem ipsum" />
<Company ID="22" Name="Company name 2" Descri开发者_Python百科ption="Lorem ipsum" />
<Company ID="28" Name="Company name 3" Description="Lorem ipsum" />
<Company ID="31" Name="Company name 4" Description="Lorem ipsum" />
</Companies>
The modulo operator is great for things like this. Basically it divides one number by another number and returns the remainder. So 1 % 4 = 1
and 4 % 4 = 0
and 8 % 4 = 0
:
success: function(xml){
var trow = $("<tr>"), table = $("#tbl");
$(xml).find("Company").each(function(index){
var cellData = "<td width=\"33%\" valign=\"top\" ><div class=\"container\">"+
"<div class=\"item\"><a href=\"#\" title=\"\" target=\"\">"+
$(this).attr("Name")+ "</a></div>" +
"<div class=\"description\">" + $(this).attr("Description") +
"</div></div></div></td>";
$(cellData).appendTo(trow);
if( (index + 1) % 4 == 0) {
trow.appendTo(table);
trow = $("<tr>");
}
});
if(trow.is(':not(:empty)')) trow.appendTo(table);
}
});
});
I also stored $("#tbl")
in a variable to reduce the number of lookups.
精彩评论