简体   繁体   English

删除父不适用于jQuery

[英]remove parent not working in jquery

I am practicing jquery , by appending an removing input ,i succeded appending in input field but not been able to remove appended input field. 我正在练习jQuery,通过附加一个删除输入,我成功地在输入字段中附加了内容,但无法删除附加的输入字段。 i am also confused with parent() in my code. 我也对我的代码中的parent()感到困惑。

<!DOCTYPE html>
<html>
<head>
<style>
.ancestors * { 
    display: block;
    border: 2px solid lightgrey;
    color: lightgrey;
    padding: 5px;
    margin: 15px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#add').click(

function(){
$('#a').append('<div><input type="text"  name="ingre[]"><button class="remo">remove</button></div>');

});



});

$(document).ready(function(){
$(".remo").click(function(){
//alert('ok');
$(this).parent('.remo').remove();

});
});
</script>
</head>

<body class="ancestors">
<button id="add">Add</button>
<div id='a'>
<input type="text" >

</div>
</html>

Removing will not work, as you are attaching the event to all current elements that exist with the class .remo . 删除将不起作用,因为您要将事件附加到.remo类中存在的所有当前元素。 When you click Add a new element is created that does not have the handler bound, so it will not remove anything. 单击添加后,将创建一个没有绑定处理程序的新元素,因此不会删除任何内容。 The solution for this is event delegation, replace this: 解决方案是事件委托,请替换为:

$(".remo").click(function(){
    $(this).parent('.remo').remove();
});

With this: 有了这个:

$("#a").on('click', '.remo', function(){
    $(this).closest('div').remove();
});

 $(document).ready(function(){ $('#add').click(function(){ $('#a').append('<div><input type="text" name="arr[]"><button class="remo">remove</button></div>'); }); $('#a').on('click', '.remo', function(){ $(this).parent().remove(); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <body class="ancestors"> <button id="add">Add</button> <div id='a'> <input type="text" > </div> 


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM