javascript - 将多个 TD 插入表的中间

标签 javascript jquery html

我有一个包含 2-4 列和 9 行的表格。一些最右边的列有文本 (abc),一些有图像,一些两者都有,有些可能两者都没有。

我想将第 2 列的内容复制到 3 个新创建的列中,但将它们插入中间(在 abc 和图像之前,如果适用)。所以它看起来像这样:

enter image description here

这种方法:

$("table td:nth-child(2) [id$=2]").each(function(i) {
  var $newCell = $(this).wrap('<td></td>').parent();
  var $newRow = $("table td:nth-child(2) [id$=1]").eq(i).parents('tr');
  $(this).parents('tr').remove();
  if ($newRow.find("td:contains('abc')").index() > -1) {
    $newRow.find("td:contains('abc')").before($newCell);
  } else if ($newRow.find("td.img").index() > -1) {
    $newRow.find("td:contains('img')").before($newCell);
  } else {
    $newRow.find("td:contains('img')").before($newCell);
  }
});

$("table td:nth-child(2) [id$=3]").each(function(i) {
  var $newCell = $(this).wrap('<td></td>').parent();
  var $newRow = $("table td:nth-child(2) [id$=1]").eq(i).parents('tr');
  $(this).parents('tr').remove();
  if ($newRow.find("td:contains('abc')").index() > -1) {
    $newRow.find("td:contains('abc')").before($newCell);
  } else if ($newRow.find("td.img").index() > -1) {
    $newRow.find("td:contains('img')").before($newCell);
  } else {
    $newRow.find("td:contains('img')").before($newCell);
  }
});

产生以下结果:

enter image description here

FIDDLE .

最佳答案

要实现此目的,您可以使用 :nth-child 遍历每第三行,将每一行所需的 td 附加到集合中的第一行。从那里你可以 remove() 不需要的行,像这样:

for (var i = 0; i < $('table tr').length / 3; i++) {
    var $rows = $('table tr:nth-child(3n+' + i + ')');
    $rows.not(':first').addClass('remove').find('td:eq(1)').insertAfter($rows.first().find('td:eq(1)'));
}
$('table .remove').remove();

Updated fiddle

关于javascript - 将多个 TD 插入表的中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37720558/

相关文章:

javascript - jQuery 可拖动、可放置查询

php - 如何使用ajax发送带有输入类型图像的表单以防止重定向/重新加载

html - 显示图片

javascript - 用 Jasmine 测试 jQuery Hover

javascript - 按钮设置为禁用,但我仍然可以单击它

javascript - Wordpress 外部 api get 请求的延迟加载

jquery - 保护 AJAX 请求中的 'secret' key

jquery - 溢出的 div 中的第一个和最后一个可见元素

javascript - 在 Node.js 中实现 JSON Web 加密

javascript - 声明局部 javascript 变量列表的最惯用的方法是什么?