javascript - Copy the contents of one column to another in jQuery - Stack Overflow

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

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

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>

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

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>
Share Improve this question edited Nov 15, 2017 at 14:24 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Oct 26, 2011 at 3:10 JamesJames 7,54310 gold badges50 silver badges85 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 3

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

Another option. Not sure which would run faster. I simply removed the first column, since it was going to be replaced, then prepended the column of choice:

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

Check it out: here.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744723897a4590073.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信