Converting table to list grouping 3 rows
In SharePoint it has a nasty habit of using nested tables everywhere. I want to use a jQuery carousel on one of them and it does not work with tables. So I need to convert a table to a list. This is not a problem as I found some jQuery that will do it for me. Namely:
var list = $("<ul/>");
$('#tab1').find("tr").each(function() {
var p = $(this).children().map(function() {
return "<p>" + $(this).html() + "</p>";
});
list.append("<li>" + $.makeArray(p).join("") + "</li>");
})开发者_StackOverflow;
$('#tab1').replaceWith(list);
The table structure is like:
<table id="test1">
<tr><td>Help 1</td></tr>
<tr><td>Me 1</td></tr>
<tr><td>Please 1</td></tr>
<tr><td>Help 2</td></tr>
<tr><td>Me 2</td></tr>
<tr><td>Please 2</td></tr>
<tr><td>Help 3</td></tr>
<tr><td>Me 3</td></tr>
<tr><td>Please 3</td></tr>
</table>
The jQuery above converts each tr
to a li
item. But for my needs I need to group into 3 rows. So the output should be:
<ul id="test1">
<li>
<p class="p1">Help 1</p>
<p class="p2">Me 1</p>
<p class="p3">Please 1</p>
</li>
<li>
<p class="p1">Help 2</p>
<p class="p2">Me 2</p>
<p class="p3">Please 2</p>
</li>
<li>
<p class="p1">Help 3</p>
<p class="p2">Me 3</p>
<p class="p3">Please 3</p>
</li>
</ul>
So I need to add a class to each row and group them in threes. So I need to know, using the jQuery statement above, if it is possible to use a counter to iterate through the list in the children().map
function?
Try this more explicit version (fiddle):
var list = $("<ul/>");
var listitem = null;
// iterate over each cell (not each row)
$('#tab1').find("tr > td").each(function(i) {
// starting with the first item, start a new listitem every three items
// and append it to the ul
if(i%3 == 0){
listitem = $("<li/>");
list.append(listitem);
}
// append the current item as a paragraph to the listitem
var p = "<p>" + $(this).html() + "</p>";
listitem.append(p);
});
// replace the table with the ul
$('#tab1').replaceWith(list);
Try this:
var target = $("#test1");
var results = [];
target.find("tr > td").each(function(i) {
var obj = $(this);
if(i%3 == 0) results.push("<li>");
results.push("<p>");
results.push(obj.html());
results.push("</p>");
if(i%3 == 2) results.push("</li>");
});
var results_in_html = results.join("");
looks messy, but this is more runtime optimized i guess, see: http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly
You can use .slice()
to group your <tr/>
var list = $("<ul/>");
while($("#test1 tr").length > 0)
{
var td = $("#test1 tr").slice(0, 3).detach().find("td");
var nowP = td.map(function(index, elm){
return $("<p/>", {html:$(elm).text(), class:"p" + (index+1)}).get();
});
list.append($("<li/>").append(nowP));
}
$("#test1").replaceWith(list);
Example on jsfiddle
精彩评论