jquery删除从表中创建的行

时间:2015-01-13 22:03:30

标签: jquery

我有一个向表添加行的按钮。此行包含文本区域和单选按钮以及删除按钮。当我点击刚创建的删除按钮

时,如何删除创建的行?
<table id="tblAnswers">
  <tr>
    <td><textarea id="Answer1" name="Answer1" rows="2" cols="20"></textarea></td>
      <td> <input name="CorrectAnswer" id="CA" type="radio" value="0" /></td>
  </tr>
</table>
<input id="AddAnswer" type="button" value="Add Answer now" />

<script>
  var i = 1;
  $("#AddAnswer").click(function () {
    //this is to increment the answer id
    i = i + 1;

    $("#tblAnswers").append('<tr> <td><textarea id="Answer' + i + '" name="Answer' + i + '" rows="2" cols="20"></textarea></td><td> <input name="CorrectAnswer" id="CA" type="radio" value="0" /></td><td><div class="delete" id="bd" style="background-image: url(../Images/delete.png); height: 28px; width: 28px; " onclick="javascript:deleterow();"> </div> </td></tr>');
  });            
</script>

我也尝试过以下但它没有工作

<script>
function deleterow(){
  $('table.actionsteps-list').on('click', '.delete', function (e) {
    e.preventDefault(); // stops the page jumping to the top
    $(this).closest('tr').remove();
  });
}
</script>

1 个答案:

答案 0 :(得分:1)

当您使用委托事件(为.click()方法提供选择器)时,您不需要onclick中的deleteRow函数:

 var i = 1;
 $("#AddAnswer").click(function() {

     //this is to increment the answer id
     i = i + 1;


     $("#tblAnswers").append('<tr><td><button class="delete">Delete</button></td></tr>');
 });

 $('#tblAnswers').on('click', '.delete', function (e) {
     $(this).closest('tr').remove();
 });

请参阅小提琴:http://jsfiddle.net/svsf0r98/

另请参阅委派活动下的http://api.jquery.com/on/

当动态添加元素时,通常会使用委托事件。没有委托事件的方法是:

 var i = 1;
 $("#AddAnswer").click(function() {

     //this is to increment the answer id
     i = i + 1;


     $("#tblAnswers").append('<tr><td><button onclick="deleteRow(this)">Delete</button></td></tr>');
 });

 function deleteRow(button) {
     $(button).closest('tr').remove();
 }

http://jsfiddle.net/9u9L84ab/1/