使用jQuery将<td>替换为<tr><td>

3

我在这里做一个懒惰的表格转置。 我有一个像这样的表格:

     <table>
     <th style="text-align: left; text-transform: capitalize;">Unique</th>
     <th style="text-align: left; text-transform: capitalize;">x1</th>
     <th style="text-align: left; text-transform: capitalize;">y2</th>
     <tr class="rowNormal">
     <td nowrap="true">a1</td>
     <td nowrap="true">b2</td>
     <td nowrap="true">b3</td>
     </tr>
     </table>

我需要让它看起来像这样:

     <table>
     <tr class="rowNormal">
     <tr><td nowrap="true">a1</td><.tr>
     <tr><td nowrap="true">b2</td></tr>
     <tr><td nowrap="true">b3</td></tr>
     </tr>
     </table>

它只有两行,其中之一是标题行。 因此我这样隐藏标题行:

        $("table:contains('Unique')").find("th").addClass("hidden");

这段代码目前运行良好。现在我需要为每个<td nowrap="true">添加一个<tr>,但是我在这里遇到了麻烦。我尝试使用以下代码:

       $('div.content').html($('div.content').html().replace(/<td nowrap="true">/g,' <tr><td nowrap="true">'));

这段代码是可行的,但我想将其限定在包含“Unique”的表格中,而不使用全局变量。 这样:

       $('div.content').html($('div.content').html().replace(/</td>/g,'<td></tr>'));

完全不起作用。 我尝试使用replaceWithreplaceAll,但未能成功。 问题: 1)最佳方法是添加格式以将剩余行转置为列吗? 2)我如何指定"/作为参数? 3)'"之间有什么区别?

感谢您的时间。


你可能只需要在第三个正则表达式中转义你的 / - Sanchit
2
你尝试过使用 $('td').wrap('tr') 吗? - Pedro Estrada
你能否编辑你的问题,包括你正在尝试生成的HTML代码? - Dan Blows
1个回答

4
你可以使用jQuery中的wrap来实现这个功能:
$("td[nowrap='true']").wrap("tr");

或者仅使用您的唯一包含选择器选择项:

$("table:contains('Unique') td[nowrap='true']").wrap("tr");

1
是的,那就是我要写的,但是将其嵌套在$("table:contains('Unique')").each()循环内部,这样它只会在他想要的表格中运行。 - VVV
哇,wrap 是一个强大的运算符,感谢你提出来。不过我左边多了一行空白?这是来自第一个 tr class="rowNormal" 吗? - Easy Life

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接