使用ajax向表中添加新行

add a new row to a table with ajax

本文关键字:添加 新行 ajax 使用      更新时间:2023-10-07

我有点问题。事实上,我意识到每次添加一行时,都会考虑到其他添加。也就是说,如果我加一行,好吧,它被插入点击的下面。但如果我想在新的下面添加,它实际上添加了两行等等。有什么帮助吗?这是我的代码

<script>

$(".insertRow").live('click', function () {
    var vref = '@Url.Action("RecordEntryRow", "Layout")';
    var obj = this;
    $.ajax({
        url: vref,
        cache: false,
        success: function (html) {
            var u = $(obj).parents(".record:first.")[0];
            $(u).after(html);
        }
    });
    return false;
});

<tr class ="record">
@using (Html.BeginCollectionItem("Records")) { 

    <td> @Html.DropDownListFor(model => model.Type, new List<SelectListItem>{
                                                    new SelectListItem() {Text = "titre en gras", Value="Titre_Gras"},
                                                    new SelectListItem() {Text = "titre normal", Value="Titre_Normal"},
                                                    new SelectListItem() {Text = "titre minime", Value="Titre_Minime"},
                                                    new SelectListItem() {Text = "titre italique", Value="Titre_Italique"},
                                                    new SelectListItem() {Text = "item", Value="Item"},
                                                    new SelectListItem() {Text = "Separateur", Value="Separateur"},
                                                    }) </td>
    <td> @Html.EditorFor(model => model.Contenu) </td>
    <td> <a href="#" onclick="$(this).closest('tr').remove();"><img src="~/Content/images/red-delete-button.jpg" width="25" height="25" /></a></td>
    <td> <a href="#" class="insertRow" ><img src="~/Content/images/add_button.png" width="20" height="20" /></a> </td>
}

我对您编辑的问题进行了测试。一切如预期:

<!doctype html>
<html>
    <head>
        <title>Test</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                var i = 0;
                $(document).off('click', '#td').on('click', 'td', function(e) {
                    $(this).parent().after('<tr><td>Append ' + i + '</td></tr>');
                    i++;
                    e.preventDefault();
                });
            });
        </script>
    </head>
    <body>
        <table>
            <tr>
                <td id="td" style="border: 1px solid red;">
                    Test
                </td>
            </tr>
        </table>
    </body>
</html>