使用jQuery修改HTML表的结构 [英] Modifying the structure of a HTML table with jQuery

查看:93
本文介绍了使用jQuery修改HTML表的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个元素列表(以下示例中的 X )显示在HTML表的行或列中.

I have a list of elements (the X in the following examples) displayed either in a row or in a column of an HTML table.

从HTML代码的角度来看,我有一个(水平显示):

In HTML code point of view, I have either (horizontal display):

<table id="myTable">
  <tr>
    <td>A</td>
    <td>B</td>
    <td>C</td>
    ...
  </tr>
</table>

或(垂直显示):

<table id="myTable">
  <tr>
    <td>A</td>
  </tr>
  <tr>
    <td>B</td>
  </tr>
  <tr>
    <td>C</td>
  </tr>
  ...
</table>

此HTML代码是由JSF组件(称为<h:selectManyCheckboxes/>)生成的,因此,我无法控制此HTML代码.

This HTML code is generated by a JSF component (called <h:selectManyCheckboxes/>), and thus, I have no control on this HTML code.

但是,我想在2列中显示元素列表. 换句话说,我表的HTML代码将是这样的:

However, I want to display my list of elements in 2 columns. In others words, the HTML code of my table will be something like that:

<table id="myTable">
  <tr>
    <td>A</td>
    <td>B</td>
  </tr>
  <tr>
    <td>C</td>
    <td>D</td>
  </tr>
  ...
</table>

如何使用jQuery做到这一点?

How can I do that using jQuery?

预先感谢您的帮助.

ps:如果您需要知道,X实际上是输入和标签,即:

ps: If you need to know, the X are in fact an input and a label, i.e.:

<td><input .../><label .../></td>

推荐答案

鉴于您提供的其他信息,我认为这就是您想要的.它遍历表格,将单元格从第二行移动到上一行...

Given the additional information you've provided, I think that this is what you want. It traverses the table moving the cells from every second row into the previous row...

var idx = 1;
var row, next;
while((row = $('#myTable tr:nth-child(' + idx++ + ')')).length) {
    if((next = $('#myTable tr:nth-child(' + idx + ')')).length) {
        row.append(next.find('td'));
        next.remove();
    }
}

这篇关于使用jQuery修改HTML表的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆