append元素不会触发事件

时间:2012-03-08 10:56:38

标签: jquery jquery-ui jquery-plugins

我想在点击“更多”后添加新的输入框和“删除”链接。也可以通过单击“删除”删除输入框。

但是,单击删除链接后,输入框不会被删除。

有没有人可以帮助他们?非常感谢!

    <script type="text/javascript">
        $(document).ready(function(){

           $('#link').click(function(){
               $('#newField').append('<input type="textbox"><a href="#" id="removeField">Remove</a><br/>');
               });
               $('#removeField').click(function(){
               $("#newField").remove();
           });
        });
    </script>

    <a href="#" id="link" title="Add field by clicking">More</a>
    <div id="newField">

    </div>

3 个答案:

答案 0 :(得分:1)

当您尝试绑定click事件时,DOM上的元素'removeField'不可用。尝试使用'on'http://api.jquery.com/on/http://api.jquery.com/live/

绑定事件

答案 1 :(得分:0)

我认为这将完成你想要做的事情:

<a href="#" id="link" title="Add field by clicking">More</a>
<div id="newField"></div>​

<script type="text/javascript">
$('#link').on('click',function() {
    $('#newField').append('<input type="textbox"><a href="#" class="removeField">Remove</a><br/>');
});
$('#newField').on('click','.removeField',function() {
    $this = $(this);
    $this.prev().remove();
    $this.next().remove();
    $this.remove();
});​
</script>

你应该在jQuery中使用.on() - 函数。

答案 2 :(得分:0)

添加字段时,不会为其添加ID,因此无法将其删除。试试这个:

$('#newField').append('<input type="textbox" id="monNewField"><a href="#" id="removeField">Remove</a><br/>');

但如果我是你,我会做这样的事情,所以你可以添加和删除任意数量的字段:

$('#newField').append('<div class="row"><input type="textbox"><a href="#" class="removeField">Remove</a></div>');

然后:

$('.removeField').click(function(){
  $(this).parent().remove();
});
相关问题