【问题标题】:Copy the contents of one column to another in jQuery在jQuery中将一列的内容复制到另一列
【发布时间】:2011-12-15 10:45:27
【问题描述】:

以下 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()
   );

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>

【问题讨论】:

    标签: javascript jquery html-table jquery-selectors


    【解决方案1】:

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

    col = 2;
    $('.grid td:first-child').remove();
    $('.grid td:nth-child('+(--col)+')').each(function(){
        $(this).parent('tr').prepend('<td>'+$(this).text()+'</td>');
    });
    

    查看:here

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 哎呀,原来的源和目标互换了。固定。
      • 酷豆。如果我将slice 更改为eq,这将有效。出于兴趣,为什么我的原始代码这么慢?
      • 哦,我省略了 slice() 的第二个参数。固定。
      • 您的原始代码分别选择每个源和目标单元格,这意味着 jQuery 需要更多的 DOM 遍历。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-25
      • 1970-01-01
      • 1970-01-01
      • 2017-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多