在当前行之后向jQuery表添加行

Pri*_*ish 3 jquery jquery-plugins

我想知道如何在我的数据表中的特定行之后添加行.我正在使用jQuery数据表插件来实现此目的.

我可以通过表行索引.我需要将行插入我的javascript函数,如下所示:

function addNewContact(rCount){ .. }

我的HTML代码是:
table id="exampleTbl"
tr
td..../td (data of first column)
td..../td (data of second column)
...
td
input type="button" id="addNewContact<%=rCount %>" name="addNewContact_Details" value="+" onclick="javascript:addNewContact(<%=rCount %>);"
/td
/tr
/table

对于新添加的行,我希望前3列为空,其他列(5)包含文本框.

Fel*_*ing 15

假设你的表看起来像这样:

<table id="exampleTbl">  
    <tr>
        <td>....</td>
        <td>....</td>
        ...  
        <td>
           <button type="button" class="addRow" />+</button>
       </td>  
    </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

您可以向添加如下行的按钮添加单击处理程序:

$(function() {
    // HTML template of a row
    var html = '<tr><td></td>...<td><button type="button" class="addRow">+</button></td></tr>';

    $('#exampleTbl').delegate('button.addRow', 'click', function() {
        var row = $(this).closest('tr'); // get the parent row of the clicked button
        $(html).insertAfter(row); // insert content
    });
});
Run Code Online (Sandbox Code Playgroud)

一些说明:

  • 由于加载了DOM,因此执行代码$(function(){...}).
  • click事件被表捕获.这确保了新插入的行的按钮也起作用.
  • 不要混合风格.如果您使用jQuery,请不要通过onclickHTML中的属性附加点击处理程序.它使您的代码难以维护,并且您可以更灵活地使用jQuery方式.

希望有所帮助,如果您对此有疑问,请对此帖发表评论.