This question already has answers here:
Event binding on dynamically created elements?
                                
                                    (23个答案)
                                
                        
                                4年前关闭。
            
                    
我在动态生成的文本框中删除按钮时遇到问题。 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/

最佳答案

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

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

09-25 16:27