删除父不在jquery中工作

时间:2015-06-04 17:59:26

标签: javascript jquery

我正在练习jquery,通过附加删除输入,我成功追加到输入字段但无法删除附加的输入字段。 我也在代码中与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>

2 个答案:

答案 0 :(得分:1)

删除将无效,因为您将事件附加到类.remo中存在的所有当前元素。单击“添加”时,会创建一个没有绑定处理程序的新元素,因此不会删除任何内容。对此的解决方案是事件委托,替换为:

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

有了这个:

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

答案 1 :(得分:1)

&#13;
&#13;
$(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();
    });
});
&#13;
<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>
&#13;
&#13;
&#13;

相关问题