使用Jquery编辑和删除新添加的表行 [英] Editing and deleting a newly added table row using Jquery

查看:106
本文介绍了使用Jquery编辑和删除新添加的表行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向现有表动态添加新行,该表的第一列包含Edit&删除按钮.我正面临2个问题:

I'm adding new rows dynamically to the existing table, the first column of the table holds the Edit & Delete buttons. I'm facing 2 problems with this:

  1. 无法编辑和删除新添加的行,尝试使用.live但无法使其正常工作
  2. 无法获取新添加的行的记录ID(添加新行时,ajax返回记录).

代码如下:

添加新行:

 <script type="text/javascript">
     $(function() {
         $('#btnSubmit').click(function() {

             var oEmployee = new Object();

             oEmployee.Title        = $("#Title").val();
             oEmployee.Middlename   = $("#MiddleName").val();
             oEmployee.Lastname     = $("#LastName").val();
             oEmployee.Email        = $("#Email").val();

             var DTO =  {'employee': oEmployee};

             var options = {
                 type: "POST",
                 url: "WebService.asmx/InsertEmployee",
                 data: JSON.stringify(DTO),
                 contentType: "application/json; charset=utf-8",
                 dataType: "json",
                 success: function(response) {
                     if (response.d != "") {
                         if (parseInt(response.d) >= 1) {
                             var contactID;
                             contactID = parseInt(response.d);
                             $('#tblEmployee tbody tr:first').after("<tr id=" + contactID + "><td><input type='button' class='newContactID' value='Edit'/>&nbsp;<input type='button' value='Delete'/></td><td align=center>" + contactID + "</td><td align=center>" + oEmployee.Title + "</td><td align=center>" + oEmployee.Middlename + "</td><td align=center>" + oEmployee.Lastname + "</td><td align=center>" + oEmployee.Email + "</td><tr>"); // need to hook up editing and deleting function to the newly added rows  }
                         else {
                             alert("Insert Failed \n" + response.d);
                         }
                     }
                 }
             };
             //Call the webservice
             $.ajax(options);
         });
     });                          
</script>

用于编辑和删除的代码:

Code for editing and deleting:

$(function() {
    $("#tblEmployee > tbody > tr ").each(function() {
        var TRID = $(this).attr("id");
        $(this).find("td:first > input[value=Edit]").click(function() {
            ResetOtherRowEdit();
            ChangeTableCellToTextbox(TRID);
            $(this).hide();
            $("#tblEmployee > tbody >  tr[id=" + TRID + "] > td:first> input[value=Delete]").hide();
            return false;
        });

        $(this).find("td:first > input[value=Update]").click(function() {
            UpdateRow(TRID);
        });

        $(this).find("td:first > input[value=Delete]").click(function() {
            DeleteRow(TRID);
        });

        $(this).find("td:first > input[value=Cancel]").click(function() {
            CancelEdit(TRID);
        });           
    });
});

解决此问题的最佳方法是什么?将记录从数据库中取出后,编辑和删除记录的效果很好.

What is the best way to approach this? Editing and deleting of records work fine when they're pulled off the database.

更新

这就是现在的代码样子,一个月前才开始涉猎Jquery,但仍在努力使它步入正轨.

This is how the code looks like now, just began dabbling with Jquery a month back, still trying to get my head around it.

    $(function() {
        $("#tblEmployee > tbody > tr ").live('click', function(e) {
            var TRID = $(this).attr("id");
            var $target = $(e.target);

            if ($target.is('#btnEdit')) {
                $(this).find("td:first > input[value=Edit]").click(function() {
                    ResetOtherRowEdit();
                    ChangeTableCellToTextbox(TRID);
                    $(this).hide();
                    $("#tblEmployee > tbody >  tr[id=" + TRID + "] > td:first> input[value=Delete]").hide();
                    return false;
                });
            }
            else if ($target.is('#btnUpdate')) {
                $(this).find("td:first > input[value=Update]").click(function() {
                    UpdateRow(TRID);
                });
            }
            else if ($target.is('#btnCancel')) {
                 $(this).find("td:first > input[value=Cancel]").click(function() {
                     CancelEdit(TRID);
                });
            }                
            else if ($target.is('#btnDelete')) {
                $(this).find("td:first > input[value=Delete]").click(function() {
                    DeleteRow(TRID);
                });
            }
        });
    });

HTML代码如下:

<ItemTemplate>
  <tr id='<%# Eval("ContactID") %>'>
        <td width="10%">                       
            <input type="button" value="Edit" id="btnEdit"/>
            <input type="button" value="Delete" id="btnDelete"/>
            <input type="button" value="Update" style="display:none" id="btnUpdate" />
            <input type="button" value="Cancel" style="display:none" id="btnCancel"/>
        </td>
        <td width="10%" align="center"><%# Eval("ContactID")%></td>
        <td width="20%" align="center"><%# Eval("Title")%></td>
        <td width="20%" align="center"><%# Eval("MiddleName")%></td>
        <td width="20%" align="center"><%# Eval("LastName")%></td>
        <td width="20%" align="center"><%# Eval("EmailAddress")%></td>
   </tr>   
</ItemTemplate>

推荐答案

您可以利用DOM遍历和.live()来完成这项工作.使用.live()将侦听器添加到表的行中.在此方法内部,确定单击了哪个元素(e.currentTarget).您可以使用简单的条件来检查它是否是需要响应的按钮.然后,使用DOM遍历确定您想要发生的事情.例如,如果e.currentTarget是删除按钮,则可以使用$(this).closest('tr').remove();删除行.如果您需要通过ajax与数据进行交互,请让ajax函数支持传递您需要执行删除操作的所有值(id).为了获取id,您需要从ajax调用中获取它并将其放置在DOM中的某个位置,以便可以在需要时检索它.生成tr时,您始终可以输入'title'属性.

You could take advantage of DOM traversal and .live() to make this work. Add a listener using .live() to the rows of the table. Inside this method, determine which element was clicked (e.currentTarget). You can use a simple conditional to check if it was a button that needs to react. Then, use DOM traversal to nail down what you want to have happen. For example, if e.currentTarget is the delete button, the you can use $(this).closest('tr').remove(); to delete the row. If you need to interact with the data through ajax, make your ajax function support passing in whatever valus you'd need (id) to perform the delete. In order to obtain the id, you'll need to get it from the ajax call and put it somewhere inside the DOM so you can retrieve it when you need it. You can always toss in a 'title' attribute when the tr is generated.

这篇关于使用Jquery编辑和删除新添加的表行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆