jquery selector iterate over children, then iterate over parent/sibling
I have the following simplified HTML Below.
<div id="coat">
<span class="Jan2011-Sales">10</span>
<span class="Feb2011-Sales">10</span>
<span class="Mar2011-Sales">10</span>
</div>
<div id="boot">
<span class="Jan2011-Sales">10</span>
<span class="Feb2011-Sales">10</sp开发者_StackOverflow中文版an>
<span class="Mar2011-Sales">10</span>
</div>
<div id="hat">
<span class="Jan2011-Sales">10</span>
<span class="Feb-Sales">10</span>
<span class="Mar2011-Sales">10</span>
</div>
<div id="etc.">
</div>
EDITED:
What I'd like to do is create a table like below: (almost like a pivot table)
<th>
<td>Period</td>
<td>Coat</td>
<td>Boot</td>
<td>Hat</td>
</th>
<tr>
<td>Jan2011-Sales</td>
<td>10</td>
<td>10</td>
<td>10</td>
<tr>
<tr>
<td>Feb2011-Sales</td>
<td>10</td>
<td>10</td>
<td>10</td>
<tr>
etc.
My question is -- how do I iterate over the original HTML? e.g. my thinking is along the lines of iterating over the first elements to get the rows, then getting the parent's sibling div so that I can find/match its child to get the columns.
Thoughts? THank you.
Here's a jsFiddle that takes your HTML data and make a table out of it: http://jsfiddle.net/jfriend00/RKBAj/.
Making these assumptions:
- Every top level div in the document is a product
- Every top level div has an ID that represents the product name
- Every span in the top level div is a month
- Every span in the top level div has a class that represents the product name
- The innerHTML of the span is the data for that product/month
- Product names can be anything (though they have to be made only our legal characters for a CSS ID).
- Month names can be anything (though they have to be made only our legal characters for a CSS class).
- There can be as many months and products as you want.
- Each product can have any number of months.
- All products don't necessarily have the same months.
Then, here's how you could iterate over the data and collect all the data into an organized data structure from which you could build a table.
// iterate over divs which we assume are products
var allProducts = [];
var allMonthsOrder = [];
function parseData() {
$("body > div").each(function() {
var allMonthsKey = {};
var product = {};
product.name = this.id;
product.months = {};
// now iterate each month in this product
$("span", this).each(function() {
var month = this.className;
product.months[month] = this.innerHTML;
// add unique months to the month array (only if we haven't seen it before)
if (!allMonthsKey[month]) {
allMonthsKey[month] = true;
allMonthsOrder.push(month); // store these in order encountered
}
});
allProducts.push(product);
});
}
// data is stored now in allProducts array
// one array element for each product
// each product is an object with a .name attribute and a .months attribute
// each .months attribute is an object where each attribute is a month name and the data for that month
The data is stored like this:
allProducts = [
{
"name": "coat",
"months": {"Jan2011-Sales": "10", "Feb2011-Sales": "10", "Mar2011-Sales": "10"},
]
},
{
"name": "boot",
"months": {"Jan2011-Sales": "10", "Feb2011-Sales": "10", "Mar2011-Sales": "10"},
},
{
"name": "hat",
"months": {"Jan2011-Sales": "10", "Feb2011-Sales": "10", "Mar2011-Sales": "10"},
}
];
And, this is one way you could create your table from the data. The tricky part of generating the table is that if any product can have any number of months and all products don't necessarily have the same months, then you have to make a row for every month that exists and fill in product data if it has data for that month.
function createTable() {
var i, j, product, month;
var html = "<table><tr>";
// iterate over the product names to make the header row
html += "<th>Month</th>";
for (i = 0; i < allProducts.length; i++)
html += "<th>" + allProducts[i].name + "</th>";
}
html += "</tr">
// now create all the rows. First column is month, then each column after that is the sales for
// a given month for a particular product (one product per columnn)
for (i = 0; i < allMonthsOrder.length; i++) {
month = allMonthsOrder[i];
html += "<tr>" + "<td>" + month + "</td>";
// iterate through each product and find if it has data for this month
for (j = 0; j < allProducts.length; j++) {
product = allProducts[j];
html += "<td>";
if (product.months[month]) {
html += product.months[month];
}
html += "</td>";
}
html += "</tr>";
}
html += "</table>";
}
var snippet = ['<table><thead><tr><th>Name</th><th>Jan-Sales</th><th>Feb-Sales</th><th>Mar-Sales</th></tr></thead><tbody>'];
$('div').each(function()
{
snippet.push('<tr><td>' + $(this).attr('id') + '</td>');
$(this).find('span').each(function()
{
snippet.push('<td>' + $(this).text() + '</td>');
});
snippet.push('</tr>');
});
snippet.push('</tbody></table>');
$('body').html( snippet.join('') );
http://jsfiddle.net/eqfEE/
You might wonder why I'm using an array instead of just doing string concatenation. The reason is very simple: array's are much faster.
When concatenating strings, JavaScript will discard the old string, and create a brand new one. This leads to too many objects being created and destroyed.
On the other hand, when using .push()
, the old array is never discarded; JavaScript merely adds a new element to the end of the array...
Now that you've updated your question and clarified that you want the product names as table headers, you should do the following:
var productsInfo = {},
periods = [],
countProducts = 0,
countPeriods = 0,
i,
snippet = ['<table><thead><tr><th>Period</th>'];
$('div').each(function()
{
var $this = $(this),
productName = $this.attr('id'),
periodsCounted = false;
productsInfo[productName] = [];
countPeriods = Math.max($(this).find('span').each(function()
{
productsInfo[productName].push( $(this).text() );
if (!periodsCounted) periods.push( $(this).attr('class') );
})
.length, countPeriods);
periodsCounted = true;
});
for ( var productName in productsInfo )
{
snippet.push('<th>' + productName + '</th>');
countProducts++;
}
snippet.push('</tr></thead><tbody>');
for(i = 0; i < countPeriods; i++)
{
snippet.push('<tr><th>' + periods[i] + '</th>');
$.each(productsInfo, function(index, e)
{
snippet.push('<td>' + e[i] + '</td>');
});
snippet.push('</tr>');
}
snippet.push('</tbody></table>');
$('body').html(snippet.join(''));
With the fiddle here: http://jsfiddle.net/eqfEE/1/
Note: this code can be improved. This is just a nudge in the right direction.
For a completely different take, you can take the existing HTML and display it with a column for each product by simply specifying this CSS:
#coat, #boot, #hat {float: left;}
.Jan-Sales, .Feb-Sales, .Mar-Sales {display: block; margin: 10px;}
This will lay out the product divs left to right and the months top to bottom in each product column.
You can see it here: http://jsfiddle.net/jfriend00/V6Dnm/
Obviously, you could use more CSS formatting to format it as a table (dividers, appropriate spacing). And, you could use JS to put column or row headers on it.
To do the selections, I ended up using 2 loops, something like this:
// first loop, get all the "months" from the first div/product
$("div#coat").each(function(idxMonth)
// second loop, get all the products and look for the matching "month"
$(this).parent().siblings().children('div' + monthClassSelector).each(function(idxSiblingMonth) {
// where monthClassSelector is something like "Jan2011-Sales" that we got from the 1st loop
精彩评论