Copy the contents of one column to another in jQuery

旧城冷巷雨未停 提交于 2019-12-23 10:19:50

问题


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>

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/7898337/copy-the-contents-of-one-column-to-another-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!