没有调用jQuery单击函数来删除动态生成的文本框

时间:2015-05-25 07:06:39

标签: javascript jquery html css click

我在动态生成的文本框上删除按钮时出现问题。点击功能根本没有被调用,我不知道为什么。有人可以指出我正确的方向吗?


这是代码:

HTML

<div class="panel panel-default">
    <div class="panel-heading">Additional Authors</div>
    <div class="panel-body">
        <input id="addAuthorButton" type="button" value="Add Author" class="btn btn-lg btn-default btn-block" />
        <div id="additionalAuthorsTextboxes">

        </div>
    </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

JS

$(document).ready(function(){

    var counter = 0;

    $("#addAuthorButton").click(function () {

        if(counter==5){
            alert("Only 5 additional authors allowed.");
            return false;
        }

        counter++;

        var newTextBoxDiv = $(document.createElement('div'))
            .attr("id", 'additionalAuthor' + counter).attr("class", 'additionalAuthor input-group');

        newTextBoxDiv.after().html("<span class='input-group-addon'><span class='glyphicon glyphicon-user'></span></span><input class='form-control' type='text' placeholder='Author Name'><span class='input-group-addon'><span style='color: red;' class='glyphicon glyphicon-remove removeAdditionalAuthor'></span></span>");

        newTextBoxDiv.appendTo("#additionalAuthorsTextboxes");

    });

    $(".removeAdditionalAuthor").click(function () {
        $(this).closest('div').remove();
    });
});

CSS

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css');
@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css');


我还设置了一个JSFiddle页面:https://jsfiddle.net/302xsar2/2/

1 个答案:

答案 0 :(得分:2)

您需要使用事件委派将事件附加到动态生成的元素:

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