2015-10-05 57 views
4

當按下加號時,我的代碼向表中添加了一行,並且它添加了正確的引用,因此當我提交表單數據時,我知道什麼是數據。減去我有點難,讓它去除剛剛添加的行或者以前從表中添加的另一行。使用jquery從表中刪除動態添加的行

我想也許它是我的.bind在addRow函數的最後一行,因爲我在這裏看到它可能應該是.on?

Issue while removing a dynamically added row from a html table using jquery

在這兩種情況下,我的代碼是在這裏:

<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> 
+0

任何控制檯錯誤? – ochi

回答

1

如何解決您的問題

  • 刪除bind();
  • 刪除removeRegularRow()函數;
  • 添加以下on('click'..事件中$(document).ready

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

測試

有很多合適的答案了。但我會爲你提供jsfiddle。我希望它有幫助。

爲什麼解決您的問題

的問題是,該行元素的動態添加後DOM已準備就緒。以一種簡單而獨特的方式,您的代碼將無法找到它。

With $('.some_parent_element').on('click', '.element_desired', function(){...});你可以繞過這個問題,並做任何你想要的元素。也就是說,讓我們堅持所有年齡的想法。 :P

您提供的link有很好的解釋。試着去理解,因爲你會需要它。你會總是需要它從這裏開始。相信我:在那裏,我仍然在那裏,我相信我會在那裏 - 可能。


爲什麼會更快地..

爲什麼最接近更快?那麼,我們have a great answer here in SO,所以我會鏈接它。但簡單來說,它圍繞搜索整個文檔或特定區域。還有需要處理的圖書館層,以最終到達你想要的地方。有一個performance test你可以看看。

文檔說:

parent()獲取每個元素的父在當前匹配的元素集合,其任選被一個選擇器過濾的。

closest()對於集合中的每個元素,通過測試元素本身並遍歷其DOM樹中的祖先,獲取匹配選擇器的第一個元素。

有些方法比parent()closest()更快,它依賴於'本地'Java腳本。但你應該考慮到可讀性以及老闆的固執性。:X

另外,考慮你的申請。可擴展性當然很重要,但即使某些東西比其他東西慢,如果你的應用程序不是很龐大,或者沒有太多的數據需要處理,也沒有太多的數據,那麼使用什麼並不重要。

+1

許多偉大的答案不知道誰來標記爲回答。我喜歡這部分原因。開始回到Jquery,而不是簡單的東西,所以這是一個好主意。我很好奇你的評論是什麼意思,它更快與$(this).closest,爲什麼不使用,如果它是更快/更好的推理是什麼? – Codejoy

+0

嗯,那只是因爲,實際上,大約兩個星期前,我工作的實習生遇到了同樣的問題,並認爲「父母」對他更有意義。所以我使用它並評論其他。 另外,'parent()'非常直接。對於一張表格,情況並非如此,但如果你出於某種原因錯誤地看到了什麼是「最接近的()」,你會得到一個不起作用的代碼,並且可能需要幾分鐘時間才能找出結果。它真的取決於大小寫,但'最接近()'更快。但要留意新的元素。 另外,教授它的[測試](http://goo.gl/EzrC7x)更快。 –

+0

但[關於它的一個很棒的問題/答案](http://goo.gl/kjR8Su)。有些方法更快。但是它需要消除代碼的'結構'/'美',因爲它不僅僅依賴於jQuery,而且還依賴於本地Java腳本 - 嗯,我不能使用這些,因爲我的老闆嚴格拒絕。爲什麼?因爲他的客戶說不。爲什麼?完全是因爲代碼中的「美」(可讀性)。所以如果可以的話,使用最快的方式! :) –

2

綁定點擊事件,像這樣: -

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

Fiddle

+0

是的,在我自己的小提琴上證實了它...作品 – ochi

0

在此行中

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

您正在觸發此代碼中的功能.bind("click", removeRegularRow(newRowID))這意味着您正在調用該函數而不是將其指定爲處理程序。

2

這條線:

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

這實際上是調用removeRegularRow()功能,並期待一個function得到恢復。

您可以通過它包裝的匿名函數內部改變:

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

當你使用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(); 
    });   
}); 

注意的關注點分離......無需內嵌代碼,無需在任何類型的循環

來處理這個
+0

Ty在處理ajax方面的位!我需要做的不是粒度級別,但我需要這樣做。 – Codejoy

2

一些事情。首先,.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和計數行等,因爲該按鈕僅查看錶行的祖先並將其刪除。簡單得多。