将表转换为列表分组3行

在SharePoint中,它有一种讨厌的习惯,即在任何地方使用嵌套表。 我想在其中一个上使用jQuery轮播,它不适用于表。 所以我需要将表转换为列表。 这不是问题,因为我发现一些jQuery会为我做这件事。 即:

var list = $("
    "); $('#tab1').find("tr").each(function() { var p = $(this).children().map(function() { return "

    " + $(this).html() + "

    "; }); list.append("
  • " + $.makeArray(p).join("") + "
  • "); }); $('#tab1').replaceWith(list);

表结构如下:

 
Help 1
Me 1
Please 1
Help 2
Me 2
Please 2
Help 3
Me 3
Please 3

上面的jQuery将每个tr转换为li项。 但是根据我的需要,我需要分成3行。 所以输出应该是:

 
  • Help 1

    Me 1

    Please 1

  • Help 2

    Me 2

    Please 2

  • Help 3

    Me 3

    Please 3

所以我需要为每一行添加一个类并将它们分成三组。 所以我需要知道,使用上面的jQuery语句,是否可以使用计数器迭代children().map函数中的列表?

试试这个更明确的版本( 小提琴 ):

 var list = $("
    "); 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 = $("
  • "); list.append(listitem); } // append the current item as a paragraph to the listitem var p = "

    " + $(this).html() + "

    "; listitem.append(p); }); // replace the table with the ul $('#tab1').replaceWith(list);

    试试这个:

     var target = $("#test1"); var results = []; target.find("tr > td").each(function(i) { var obj = $(this); if(i%3 == 0) results.push("
  • "); results.push("

    "); results.push(obj.html()); results.push("

    "); if(i%3 == 2) results.push("
  • "); }); var results_in_html = results.join("");

    看起来很乱,但这是运行时优化的更多我猜,请参阅: http : //www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly

    您可以使用.slice()

    进行分组

     var list = $("
      "); while($("#test1 tr").length > 0) { var td = $("#test1 tr").slice(0, 3).detach().find("td"); var nowP = td.map(function(index, elm){ return $("

      ", {html:$(elm).text(), class:"p" + (index+1)}).get(); }); list.append($("
    • ").append(nowP)); } $("#test1").replaceWith(list);

      关于jsfiddle的例子