[英]Jquery clone only repeating once. Need to repeat multiple times
I'm working on some existing code which is in html tables.我正在处理 html 表中的一些现有代码。 I need to copy the text from the 'th' header rows and duplicate them inside the corresponding td cells for every subsequent row.我需要从第 header 行复制文本,并将它们复制到每个后续行的相应 td 单元格中。 I have managed to get the header row to copy but it will only repeat on the first row.我设法复制了 header 行,但它只会在第一行重复。 How can I get it to repeat on every row that follows?我怎样才能让它在接下来的每一行上重复? Thanks!谢谢!
$(document).ready(function() { $('.head').each(function(i) { var $content = $('.new').eq(i); $(this).clone().prependTo($content); }); });
table, tbody, tr, th, td { border: 1px solid #000; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <table id="table-container"> <tbody> <tr class="header"> <th class="head">Header 1</th> <th class="head">Header 2</th> <th class="head">Header 3</th> <th class="head">Header 4</th> </tr> <tr class="row>"> <td class="new">Row 1</td> <td class="new">Row 2</td> <td class="new">Row 3</td> <td class="new">Row 4</td> </tr > <tr class="alt>"> <td class="new">Row 1</td> <td class="new">Row 2</td> <td class="new">Row 3</td> <td class="new">Row 4</td> </tr> </tbody> </table> </div>
Loop over the table rows except the .header
one, and then inside loop over the cells of the current row, and prepend the clone of the corresponding .head
cell.遍历除.header
之外的表格行,然后在当前行的单元格中循环,并在前面加上相应的.head
单元格的克隆。
$(document).ready(function() { $('tr:not(.header)').each(function() { $(this).find('.new').each(function(i) { $(this).prepend($('.head').eq(i).clone()); }); }); });
table, tbody, tr, th, td { border: 1px solid #000; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <table id="table-container"> <tbody> <tr class="header"> <th class="head">Header 1</th> <th class="head">Header 2</th> <th class="head">Header 3</th> <th class="head">Header 4</th> </tr> <tr class="row>"> <td class="new">Row 1</td> <td class="new">Row 2</td> <td class="new">Row 3</td> <td class="new">Row 4</td> </tr > <tr class="alt>"> <td class="new">Row 1</td> <td class="new">Row 2</td> <td class="new">Row 3</td> <td class="new">Row 4</td> </tr> </tbody> </table> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.