I have an Jquery script that loads an XML file and spits out the contents. However, I’d like to format these contents into a table, with 3 columns per row. Currently, it makes one long row and I haven’t found anything on google about calling in a new function after .each has loaded several items.
To reiterate, I want to execute function newrow() after if(hideproduct == “”){} has successfully executed 3 times.
var product_xml = "xml/products_loaded.xml"
function xmlParser() {
$.ajax({
type: "GET",
url: product_xml,
dataType: "xml",
success: function(xml) {
function newrow(){
$("#output").append("</tr><tr>")
}
$(xml).find("SAVED_EXPORT").each(function(){
var productcode = $(this).find("productcode").text()
var productname = $(this).find("productname").text()
var productprice = $(this).find("productprice").text()
var hideproduct = $(this).find("hideproduct").text()
if(hideproduct == ""){
$("#output").append("<td class='product' id='" + productcode + "'>"
+ "<a href='/i/" + productcode + ".htm' title='" + productname + ", " + productcode + "'>" + productname + "</a><br>"
+ "<span><font class='text colors_text'><b><span class='price'>Our Price</span>: </b></font> $" + productprice + "</span><br>"
+ "<img src='/v/vspfiles/photos/" + productcode + "-1.jpg' border='0' alt='" + productname + "'>"
+ "</td>");;
}
})
}
})
}
Thanks in advance for anyone who has an idea on how to solve this.
The key thing is that you need a counter variable outside of the
.eachto store state:since you can’t store state variables using local
vardeclarations inside the.eachcallback function.Then, inside the
if (hideproduct ...)block, count the number of times it was called:and if necessary, call the function
As it happens your
newRow()function won’t work anyway, because you can’t create unbalanced HTML tags using.append.A better solution would be:
Note how a new
<tr>is only created when necessary, and then the new content in your<td>elements are added directly to that, and not to#output.