删除tr jquery

时间:2016-09-28 07:04:42

标签: javascript jquery html

我有一个jquery在表中追加行。但我发现很难删除该行。 我应该在父母标记中删除哪一行?

  

e.preventDefault(); $(本).parent(' TR')。remove()方法; X - ;



$(document).ready(
  function (){
    var max_fields = 10; //maximum input boxes allowed
    var wrapper = $(".input_fields_wrap"); //Fields wrapper
    var add_button = $(".add_field_button"); //Add button ID

    var x = 1; //initlal text box count
    $(add_button).click(
      function (e){ //on add input button click
        e.preventDefault();
        if (x < max_fields)
        { //max input box allowed
          x++; //text box increment
          $(wrapper)
          .append('<tr><td><input type="text" name="mytext[]"/></td> <td><a href="#" class="remove_field">Remove</a></td></tr>'); //add input box
        }
      }
    );

    $(wrapper).on(
      "click",
      ".remove_field",
      function (e){ //user click on remove text
        e.preventDefault();
        $(this)
        .parent('tr')
        .remove();
        x--;
      }
    );
  }
);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table class="input_fields_wrap" border="1">
  <tr>
    <td><input type="text" name="mytext[]" /></td>
    <td><a href="#" class="remove_field">Remove</a></td>
  </tr>
  <button class="add_field_button">Add More Fields</button>
</table>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:2)

试试这个

 $(this).parent().closest('tr').remove();

在您的案例中替换此代码

$(wrapper).on("click",".remove_field", function(e){ //user click on remove text        
        e.preventDefault();  $(this).parent().closest('tr').remove(); x--;
    })

Working example for your scenario

答案 1 :(得分:1)

使用

    $(this).parents('tr').remove();

而不是

    $(this).parent('tr').remove();

答案 2 :(得分:0)

wrapper中停止包裹add_button$(),在变量声明期间将其换行一次,足够

答案 3 :(得分:0)

试试这个: -

<html>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
var max_fields      = 10; //maximum input boxes allowed
var wrapper         = $(".input_fields_wrap"); //Fields wrapper
var add_button      = $(".add_field_button"); //Add button ID

var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
    e.preventDefault();
    if(x < max_fields){ //max input box allowed
        x++; //text box increment
        $(wrapper).append('<tr><td><input type="text" name="mytext[]"/></td> <td><a href="javascript:void(0)" class="remove_field">Remove</a></td></tr>'); //add input box
    }
});

$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
     $(this).closest('tr').remove(); x--;
})
});

</script>
<style>


</style>
</head> 

<body>


<table class="input_fields_wrap" border="1">
<tr><td><input type="text" name="mytext[]"/></td><td><a href="#"class="remove_field">Remove</a></td></tr>
<button class="add_field_button">Add More Fields</button>
 </table>



</body>
</html>