2013-07-31 96 views
0

我對jquery很新,我想添加和刪除表格行 單擊添加或刪除圖像。無法刪除動態添加的表格

添加按鈕完美地工作,手動添加的行與刪除按鈕完美地工作,但如果我添加一個新行,然後單擊新行的刪除按鈕,它什麼都不做。

我試過搜索谷歌和測試所有的答案,但似乎沒有爲我工作。

<script type="text/javascript"> 
      $(document).ready(function(){ 
        var idCount = 0; 
        idCount++; 
        var new_row="<tr><td><span style='float:left; margin-left:20px;'>IP:&nbsp;</span><input name='ipaddr' type='text' /></td><td><img src='images/delete.png' width='20px' height='20px' id='deleteRow' /></td></tr>"; 
        $("table#ipList img#addRow").click(function() { 
          $("table#ipList").append(new_row); 
        }); 
        $("table#ipList img#deleteRow").click(function() { 
          //$("img#deleteRow").parents("tr").remove(); 
          //$("img#deleteRow").parent().parent().last().remove(); 
          $("img#deleteRow").last().parent().parent().remove(); 
        }); 
      }); 
    </script> 
    </head> 
    <body> 
    <table id="ipList"> 
      <tr> 
        <td><span style="float:left; margin-left:20px;">IP:&nbsp;</span><input name="ipaddr" type="text" /></td> 
        <td><img src="images/add.png" width="20px" height="20px" id="addRow" /></td> 
      </tr> 
      <tr> 
        <td><span style="float:left; margin-left:20px;">IP:&nbsp;</span><input name="ipaddr" type="text" /></td> 
        <td><img src="images/delete.png" width="20px" height="20px" id="deleteRow" /></td> 
      </tr> 
    </table> 
+0

爲什麼你有var new_row評論? – Sergio

+0

而且,如果ID是唯一的,你不需要'table#ipList img#addRow','#addRow'就足夠了。 – Sergio

回答

3

使用代表團是這樣的:

但ID必須是上下文頁面上獨一無二的!

$(document).ready(function() { 
    var idCount = 0; 
    idCount++; 
    $("#ipList").on('click', "#addRow", function() { 
     $("#ipList").append(new_row); 
    }); 
    $("#ipList").on('click', "#deleteRow", function() { 
     $("#deleteRow").closest('tr').remove(); 
    }); 
    }); 
+0

哇感謝,像一個魅力工作:) 最後一個問題,我怎麼能追加idCount到新的投入類。 – Sayajin