使用 jQuery 插入表格列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1655319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:56:27  来源:igfitidea点击:

Inserting a table column with jQuery

jqueryhtml-table

提问by Mottie

I have a table of data that I need to dynamically add a column to. Lets say I have this basic table to start with:

我有一个数据表,我需要向其中动态添加一列。假设我有这个基本表开始:

<table>
 <tr><td>cell 1</td><td>cell 2</td><td>cell 3</td></tr>
 <tr><td>cell 1</td><td>cell 2</td><td>cell 3</td></tr>
 <tr><td>cell 1</td><td>cell 2</td><td>cell 3</td></tr>
</table>

I would like to insert a column between cell 1 and cell 2 in each row... I've tried this but it just isn't working like I expect...

我想在每一行的单元格 1 和单元格 2 之间插入一列......我已经尝试过这个,但它不像我预期的那样工作......

$(document).ready(function(){
 $('table').find('tr').each(function(){
  $(this).prepend('<td>cell 1a</td>');
 })
})

回答by Dan Herbert

Try this:

尝试这个:

$(document).ready(function(){
    $('table').find('tr').each(function(){
        $(this).find('td').eq(0).after('<td>cell 1a</td>');
    });
});

Your original code would add the column to the end of each row, not in between columns. This finds the first column and adds the cell next to the first column.

您的原始代码会将列添加到每行的末尾,而不是列之间。这将找到第一列并在第一列旁边添加单元格。

回答by Stefan Kendall

$('table > tr > td:first-child').after( '<td>cell 1a</td>' );

tr > tdselects the first-level tdafter a tr, and afterinserts data outside the element.

tr > td选择tda 之后的第一级tr,并after在元素外插入数据。

回答by lwpro2

$('td:first-child').after('&lt;td&gt;new cell&lt;/td&gt;');