开发者

Inserting a table column with jQuery

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:

<开发者_如何学JAVA;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...

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


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.


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

tr > td selects the first-level td after a tr, and after inserts data outside the element.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜