在jQuery中将一列的内容复制到另一列 [英] Copy the contents of one column to another in jQuery

查看:147
本文介绍了在jQuery中将一列的内容复制到另一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下jQuery非常慢(约7秒)。我显然做错了!

The following jQuery is extremely slow (~7 sec). I'm clearly doing it the wrong way!

我正在尝试将列 col 的内容复制到HTML表中的列 0
因此如果col为2,那么我需要将第2列复制到第0列。

I'm trying to copy the contents of column col to column 0 in an HTML table so if col is 2, then I need to copy column 2 to column 0.

for (var i=0;i<31;i++)
  $('.grid tr:nth-child(' + i + ') td:first-child').text(
    $('.grid tr:nth-child(' + i + ') td:nth-child(' + col + ')').text()
   );

HTML:

<table>
  <tr><td>A</td><td>D</td><td>G</td></tr>
  <tr><td>B</td><td>E</td><td>H</td></tr>
  <tr><td>C</td><td>F</td><td>I</td></tr>
  <!-- etc. -->
</table>


推荐答案

您无需单独选择每个表格单元格。您可以选择源列和目标列并迭代它们:

You don't need to select each table cell individually. You can select the source column and destination columns and iterate over them:

// Get the target column table cells.  This will select the first cell from
// each row in the table.
var target = $('.grid tr td:first-child');

// Iterate over each cell in the source column and copy its text to the
// corresponding cell in the target column.
$('.grid tr td:nth-child(' + (col + 1) + ')').each(function (rowIndex) {
    target.slice(rowIndex, rowIndex + 1).text($(this).text());
});

这篇关于在jQuery中将一列的内容复制到另一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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