2016-12-31 217 views
1

如果单击删除行按钮,表格行将被删除。单击按钮时删除表格行

如果点击添加按钮,新的字段和删除行按钮将被添加到表体中。

我面临的问题是,删除行按钮在我的HTML,但不是在我的JavaScript。请帮忙。

<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> 
 

 
    <!-- jQuery library --> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 

 
    <!-- Latest compiled JavaScript --> 
 
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 
 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
 
    <title>Page 2</title> 
 

 
</head> 
 

 
<body> 
 
    <table id="table"> 
 
    <tbody> 
 
     <tr> 
 
     <td>Field 1 
 
      <input type="text" name="field1"> 
 
     </td> 
 
     <td> 
 

 
      <button class="btn removemebtn">Remove Row!</button> 
 
     </td> 
 
     </tr> 
 
    </tbody> 
 
    </table> 
 

 
    <button class="btn" id="addbtn">Add</button> 
 

 
    <script type="text/javascript"> 
 
    $(document) 
 
     .ready(
 
     function() { 
 
      $('#addbtn') 
 
      .click(
 
       function() { 
 
       $('tbody') 
 
        .append(
 
        '<tr>' + '<td>' + 'Field 2 <input type="text" name="field2">' + '</td>' + '<td>' + '<button class="btn removemebtn">Remove Row!!' + '</button>' + '</td>' 
 

 
        + '</tr>'); 
 
       }); 
 

 
      $('.removemebtn').click(function() { 
 
      $(this).closest('tr').remove(); 
 
      }); 
 
     }); 
 
    </script> 
 
</body> 
 

 
</html>

回答

1

,因为你在$(document).ready ({/*..*/})设置的事件侦听器.removebtn您遇到的问题时,所以当您删除行,新按钮不会有相同的事件监听器。

将您的删除功能包装到函数中,并在调用该函数的每一行上设置onclick属性。

相关问题