如何使用JQuery将新的TR插入HTML表格的中间位置?

8

我知道如何使用JQuery在表格中添加新行:

var newRow = $("<tr>..."</tr>");
$("#mytable tbody").append(newRow);

问题是如何创建一个在某个现有行之前的新行。

5个回答

9
var newRow = $("<tr>...</tr>");
$("#idOfRowToInsertAfter").after(newRow);

关键在于知道要插入新行的行id,或至少想出一些选择器语法,以获取该行。

jQuery的after()文档


7
where_you_want_it.before(newRow)

或者

newRow.insertBefore(where_you_want_it)

-- MarkusQ


请使用 .after() 代替! - Heitor

5

不是这样的:

$("#mytable tbody").append(newRow);

你将要做的事情类似于这样:

$("#id_of_existing_row").after(newRow);

5

使用:

var newTr = $('<tr>[...]</tr>');

您可以...

  1. Insert it after (or before if you so choose) another row for which you know an ID (or whatever other property):

    $('#<id of the tr you want to insert the new row after>').after(newTr)
    
  2. Insert it after a particular row index (indices are 0-based, not 1-based):

    $($('table#<id> tr')[<index>]).after(newTr)
    
  3. …or as you mentioned, the absolute middle is possible:

    var existingTrs = $('table#<id> tr')
    $(existingTrs[parseInt(existingTrs.length / 2)]).after(newTr)
    

0
如果您在表格中插入一张图片,代码将类似于以下内容:
表格中的最后一个单元格:
 <td> <img class=\"insertRow\" src=\"/images/imgInsertRow.jpg\" /> </td>

你的 jQuery 代码:

$('table td img.insertRow').click(function(){
   var newRow=$('<tr>........</tr>');
   $(this).parent().parent().after(newRow);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接