" X"从动态表单中删除字段

时间:2014-06-17 08:46:04

标签: jquery tags

我想在表单中动态添加和删除字段,如下所示:  enter image description here

这是我的代码: JQuery的

$('#addFeild').click(function(){
    $('#divTest').append("<div> <input name='titres' type='text'/> <a href='#' id='close_box'>x</a>  </div>");
});

$('#close_box').click(function(){
    $(this).parent().remove();
});

JSP:

<html:form action="/test.do">
    <div id="divTest">
    </div>
    <a href="#" id="addFeild">+</a> 
    <html:submit property="submit" value="Submit"/>
</html:form>

我使用this示例,但它不起作用!! 任何帮助表示赞赏:)

5 个答案:

答案 0 :(得分:1)

该示例清楚地显示了要实施的event delegation,而您还没有这样做!

所以试试这个:

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

但我建议您为关闭框创建唯一ID,因为ID必须是唯一的,或者使用类而不是ID

$('#divTest').append("<div> <input name='titres' type='text'/> <a href='#' class="close_box">x</a>  </div>");


$("#divTest").on('click','.close_box',function(){  // with class 
    $(this).closest('div').remove();
});

答案 1 :(得分:1)

使用 event delegation

  • 事件委托允许我们将单个事件监听器附加到 父元素,将为匹配a的所有后代触发 选择器,无论这些后代现在存在还是被添加到 未来。

 $("#divTest").on("click","#close_box",function(e){
        e.preventDefault();
        $(this).parent().remove();
    });

答案 2 :(得分:1)

这称为event delegation问题,只要事件绑定到动态生成的元素,那么该事件需要委托给最近的静态父类,如:

$('#divTest').on('click', '#close_box', function(){
    $(this).parent().remove();
});

而不是.parent()您也可以使用.closest()

$(this).closest('div').remove();

event delegation的语法如下:

$(staticparent).on(event, selector, callback);

注意:

如果您没有委托给最近的静态父级,那么您不需要将绑定事件放在doc ready块中。

由于此答案建议使用最接近的静态父级,然后,您必须将该事件放入doc ready块

所以试试这个:

$(function(){ // doc ready
   $('#divTest').on('click', '#close_box', function(){
       $(this).parent().remove();
   });
}); // doc ready ends

答案 3 :(得分:0)

当您动态添加元素时,如果您希望在事件上触发它,则应该为其添加一个事件侦听器:

$(document).on('click','#close_box',function(){
    $(this).parent().remove();
});

答案 4 :(得分:0)

试试这个?

$('#close_box').click(function(){
    $(this).closest('div').remove();
});