使用jquery从表中删除动态添加的行

Removing dynamically added row from a table using jquery

本文关键字:动态 添加 删除 jquery 使用      更新时间:2023-09-26

我的代码在加号按下时向表添加一行,并且它添加了正确的引用,因此当我提交表单数据时,我知道什么数据是什么。减去我有一点困难,让它在删除刚刚添加的行或另一行以前添加的表工作。

我想也许是addRow函数最后一行的。bind就像我在这里看到的它可能应该是。on ?

使用jquery从html表中删除动态添加行的问题

无论哪种情况,我的代码都在这里:

   <script language='javascript' type='text/javascript'>
        $(document).ready(function () {
            function addRow() {
                var $myTable = $("#myTable").find('tbody');
                var parent = $(this).parent("td").parent("tr").attr("id");
                var newRowID = $myTable.children("tr").length + 1;
                var $newRow = $("<tr id='regFacEmpType" + newRowID + "' data-parent-row='" + parent + "'>");
                $newRow.append($("<td align='center'>611000</td>"));
                $newRow.append($("<td class='style1'><input type='text' name='RegEmpType" + newRowID + "' size='15' data-emp-type='Regular' /></td>"));
                //see the data-emp-type not sure how else to know what is coming back unless name is going to be dynamically generated here using  a counter.  Should
                //only be one type of each field, so instead of EmpType being generic:  EmpTypeRegular1 and if they add another employee then EmpTypeRegular2 etc.
                $newRow.append($("<td><input type='checkbox' name='RegEmpIDC" + newRowID + "' value='true' /></td>"));
                $newRow.append($("<td align='center' id='RegEmpAgencyBudgt" + newRowID + "'>$43,0000</td>"));
                $newRow.append($("<td align='center' id='RegEmpRowBdgt" + newRowID + "'>$3,0000</td>"));
                $newRow.append($("<td class='style1' id='RegEmpRowAdjBudget" + newRowID + "'><input type='text' name='AdjustedBudgetRegularEmpType" + newRowID + "' /></td>"));
                $newRow.append($("<td class='style1' id='RegEmpRowComments" + newRowID + "'><input type='text' name='RegEmpComments" + newRowID + "' /></td>"));
                $newRow.append($("<td></td>").append($("<button class='addRegular' type='button'>+</button>").bind("click", addRow))); //make it where any plus subsequently added will add a row
                $newRow.append($("<td></td>").append($("<button class='removeRegular' id='removeRegular" + newRowID +"' type='button'>-</button>").bind("click", removeRegularRow(newRowID))));
                $myTable.append($newRow);
            };

            //for some reason this is called everytime I click the PLUS also it does nothing?
            function removeRegularRow(index) {
                        $("#regFacEmpType" + index).remove();
            };

            $(".addRegular").on("click", addRow); //make it so the default row adds a new one.
        });
</script>
</head>
<body>
    <FORM action="" method="post">
    <table id='myTable'>
            <tbody>
                <tr id="FacultyEmployees">
                    <th align="center" class="style1">Index Number</th>
                    <th align="center" class="style1">Faculty Type</th>
                    <th align="center" class="style1">IDC</th>
                    <th align="center" class="style1">Agency Budgeted Amount</th>
                    <th align="center" class="style1">PI Budgeted Amount</th>
                    <th align="center" class="style1">PI Adjusted Budget</th>
                    <th align="center" class="style1">Comments</th>
                </tr>
                <tr id="regFacEmpType1" data-child-type='regExemptEmpType1' data-parent-type='regFacEmpType1'>
                    <!-- next row would be regExemptEmpType1 etc -->
                    <td align="center">611000</td>
                    <td align="center">Regular</td>
                    <td><input type="checkbox" name="IDC" value="true" /></td>
                    <td align="center" id="agencyBudgeted1">$43,0000</td>
                    <td align="center" id="piBudgetedAmount1">$33,0000</td>
                    <td id="piAdjustedBudget1"><input type="text" name="PI Adjusted Budget" width="5" /></td>
                    <td class="style1"><input type="text" name="Comments" id="comments1" size="15" /></td>
                    <td><button type='button' class="addRegular">+</button></td>                    
                </tr>
            </tbody>
        </table>
        <button type="submit"/> Submit </button>
        </FORM>

解决问题

关于JavaScript代码:

  • 删除bind()功能;
  • 取消removeRegularRow()功能;
  • $(document).ready中添加以下on('click'..事件:

    $("#myTable").on('click', '.removeRegular', function(){
        $(this).parent().parent().remove();
        // It's faster with: $(this).closest('tr').remove();
    });
    

为什么这解决了手头的问题

问题是这一行元素是动态插入的,并且只有在DOM加载了所有元素并准备好之后才会插入。用一种简单的方法,你的算法不会找到想要插入的HTML,所有内容都已加载

使用$('.some_parent_element').on('click', '.element_desired', function(){...});,您可以绕过这个问题,对元素做任何您想做的事情。也就是说,让我们坚持适合所有年龄的想法,好吗?: P

你提到的答案有一个很好的和简洁的解释。试着理解这个答案,因为你将需要理解未来的编码。

为什么使用closest更快

好吧,我们在这里有一个很好的答案来解释"为什么",所以我将链接到它。但是,总的来说,是围绕搜索整个文档或文档的特定区域展开的。此外,还需要处理库层,以便最终得到您想要的结果。作为附录,请检查此性能测试。

docs表示:

parent() 获取当前匹配元素集合中每个元素的父元素,可由选择器筛选。

closest() 对于集合中的每个元素,通过测试元素本身并遍历其在DOM树中的祖先,获得与选择器匹配的第一个元素。

有比parent()closest()更快的方法,依赖于"本地"Java脚本。但是你应该始终考虑可读性以及老板和客户的固执…

还要考虑应用程序的目标受众。当然,可伸缩性很重要,但即使某些东西比其他东西慢,如果您的应用程序不是很大或没有很多数据要处理,那么您使用什么并不重要。只要确保适当地利用它,并在需要时不断进行更改。

测试重写的代码

您可以验证更改后的代码现在是否正常工作。点击下面的"运行代码片段"按钮。

$(document).ready(function () {
    		var index;
    
            function addRow() {
                var $myTable = $("#myTable").find('tbody');
                var parent = $(this).parent("td").parent("tr").attr("id");
                var newRowID = $myTable.children("tr").length + 1;
                index = newRowID;
                var $newRow = $("<tr id='regFacEmpType" + newRowID + "' data-parent-row='" + parent + "'>");
                $newRow.append($("<td align='center'>611000</td>"));
                $newRow.append($("<td class='style1'><input type='text' name='RegEmpType" + newRowID + "' size='15' data-emp-type='Regular' /></td>"));
                //see the data-emp-type not sure how else to know what is coming back unless name is going to be dynamically generated here using  a counter.  Should
                //only be one type of each field, so instead of EmpType being generic:  EmpTypeRegular1 and if they add another employee then EmpTypeRegular2 etc.
                $newRow.append($("<td><input type='checkbox' name='RegEmpIDC" + newRowID + "' value='true' /></td>"));
                $newRow.append($("<td align='center' id='RegEmpAgencyBudgt" + newRowID + "'>$43,0000</td>"));
                $newRow.append($("<td align='center' id='RegEmpRowBdgt" + newRowID + "'>$3,0000</td>"));
                $newRow.append($("<td class='style1' id='RegEmpRowAdjBudget" + newRowID + "'><input type='text' name='AdjustedBudgetRegularEmpType" + newRowID + "' /></td>"));
                $newRow.append($("<td class='style1' id='RegEmpRowComments" + newRowID + "'><input type='text' name='RegEmpComments" + newRowID + "' /></td>"));
                $newRow.append($("<td></td>").append($("<button class='addRegular' type='button'>+</button>").bind("click", addRow))); //make it where any plus subsequently added will add a row
                $newRow.append($("<td></td>").append($("<button class='removeRegular' id='removeRegular" + newRowID +"' type='button'>-</button>")));
                $myTable.append($newRow);
            };
    		$("#myTable").on('click', '.removeRegular', function(){
            	$(this).parent().parent().remove();
            
            });
            $(".addRegular").on("click", addRow); //make it so the default row adds a new one.
        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<FORM action="" method="post">
    <table id='myTable'>
            <tbody>
                <tr id="FacultyEmployees">
                    <th align="center" class="style1">Index Number</th>
                    <th align="center" class="style1">Faculty Type</th>
                    <th align="center" class="style1">IDC</th>
                    <th align="center" class="style1">Agency Budgeted Amount</th>
                    <th align="center" class="style1">PI Budgeted Amount</th>
                    <th align="center" class="style1">PI Adjusted Budget</th>
                    <th align="center" class="style1">Comments</th>
                </tr>
                <tr id="regFacEmpType1" data-child-type='regExemptEmpType1' data-parent-type='regFacEmpType1'>
                    <!-- next row would be regExemptEmpType1 etc -->
                    <td align="center">611000</td>
                    <td align="center">Regular</td>
                    <td><input type="checkbox" name="IDC" value="true" /></td>
                    <td align="center" id="agencyBudgeted1">$43,0000</td>
                    <td align="center" id="piBudgetedAmount1">$33,0000</td>
                    <td id="piAdjustedBudget1"><input type="text" name="PI Adjusted Budget" width="5" /></td>
                    <td class="style1"><input type="text" name="Comments" id="comments1" size="15" /></td>
                    <td><button type='button' class="addRegular">+</button></td>                    
                </tr>
            </tbody>
        </table>
        <button type="submit"/> Submit </button>
        </FORM>

当您在页面中遇到多个重复元素时,使用ID来定位元素是最不可取的方法。

试图使ID匹配变得复杂得多,而基于重复元素的类和结构进行遍历要简单得多。

一个处理程序也可以管理所有重复元素。下面的代码可以放在代码库的任何地方…每次页面加载一次

$(document).on('click','.removeRegular', function(){
     $(this).closest('tr').remove();  
});

然后在tr上,你可以添加一个数据库标识符,可以用于ajax请求

<tr data-id="serverIdValue">

并升级处理程序:

$(document).on('click','.removeRegular', function(){
     var $row = $(this).closest('tr'), rowId = $row.data('id');
     // only remove once server update confirmed
     $.post('/api/row/delete', {id: rowId}, function(response){
          // validate response first then remove the row
          $row.remove();
     });          
});

注意关注点的分离…不需要内联代码,也不需要在任何循环中处理这个

像这样绑定你的点击事件:-

$newRow.append($("<td></td>").append($("<button class='removeRegular' id='removeRegular" + newRowID +"' type='button'>-</button>").bind("click", function(){ removeRegularRow(newRowID); })));

小提琴

这条线:

.bind("click", removeRegularRow(newRowID))

这实际上是调用removeRegularRow()函数并期望返回function

你可以通过将它包装在一个匿名函数中来改变它:

.bind("click", function() { removeRegularRow(newRowID) })

有几件事。首先,.bind()不再是添加处理程序的首选方法。从jQuery 1.7开始,.on()是最好的方法。其次,在这段代码中:

.bind("click", removeRegularRow(newRowID))

实际上是在附加处理程序时调用removeRegularRow,并将返回值附加到click事件。这显然不是你想要的。你想传递一个函数引用:

.on("click", function(){ removeRegularRow(newRowID); } ))

然而,更好的是附加一个处理程序,使用表本身作为委托并过滤removeRegular按钮类:

$('#myTable').on('click', '.removeRegular', function() {
    $(this).parent().closest('tr').remove();
});

使用单个处理程序,因为它附加到表而不是行,所以您不必担心添加和删除元素时会发生什么(只要表始终存在)。您也不必担心跟踪ID和计数行等问题,因为按钮只是查看作为表行的祖先并将其删除。更加简单。

这一行

$newRow.append($("<td></td>").append($("<button class='removeRegular' id='removeRegular" + newRowID +"' type='button'>-</button>").bind("click", removeRegularRow(newRowID))));

您正在触发此代码.bind("click", removeRegularRow(newRowID))中的函数,这意味着您正在调用该函数而不是将其指定为处理程序。