Javascript 在jQuery中将一列的内容复制到另一列

Javascript 在jQuery中将一列的内容复制到另一列,javascript,jquery,html-table,jquery-selectors,Javascript,Jquery,Html Table,Jquery Selectors,下面的jQuery非常慢(约7秒)。很明显,我做得不对 我试图将列col的内容复制到HTML表中的列0 所以如果col是2,那么我需要将第2列复制到第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() ); for(var i

下面的jQuery非常慢(约7秒)。很明显,我做得不对

我试图将列
col
的内容复制到HTML表中的列
0
所以如果col是2,那么我需要将第2列复制到第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()
   );

for(var i=0;i您不需要单独选择每个表单元格。您可以选择源列和目标列并对其进行迭代:

// 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());
});

另一个选项。不确定哪一个运行得更快。我只是删除了第一列,因为它将被替换,然后在选择的列前面加上前缀:

col = 2;
$('.grid td:first-child').remove();
$('.grid td:nth-child('+(--col)+')').each(function(){
    $(this).parent('tr').prepend('<td>'+$(this).text()+'</td>');
});
col=2;
$('.grid td:first child').remove();
$('.grid td:n个子('+(-col)+')。每个(函数(){
$(this.parent('tr').prepend(“”+$(this.text()+“”);
});

查看:。

哎呀,原来是源代码和目标代码交换了。修复了。很酷的bean。如果我将
slice
更改为
eq
,这会起作用。出于兴趣,我的原始代码为什么这么慢?哦,我省略了slice()的第二个参数.Fixed。您的原始代码分别选择每个源单元格和目标单元格,这意味着jQuery需要进行更多的DOM遍历。
col = 2;
$('.grid td:first-child').remove();
$('.grid td:nth-child('+(--col)+')').each(function(){
    $(this).parent('tr').prepend('<td>'+$(this).text()+'</td>');
});