JS动态添加字段 - 删除按钮不起作用

时间:2016-05-17 14:16:53

标签: javascript jquery html

问题是我然后动态添加一些输入字段,应该删除添加的行的单击操作不起作用。我知道点击动作必须使用.on但它没有帮助。有什么想法吗?

这是.js文件:

    $(document).ready(function() {

    $('.eventsRowsWrapper').each(function() {
        var $wrapper = $('.eventsRows', this);

        $(".addEventButton", $(this)).on('click', function() {
            //console.log(jsFrontend.data.get('Planning.test'));
            //$('.multi-event:first-child').clone(true).appendTo($wrapper).find('input').val('').attr('id', '');
            $($wrapper).append('<div class="form-group multi-event controls form-inline"> <input name="date[]" maxlength="255" type="text" placeholder="Data" class="datepickerClass form-control sortable ui-sortable" size="20"> <button type="button" style="float: none" class="close deleteEventButton">&times;</button></div>');
            $(".datepickerClass").datepicker();
            $('.sortable').sortable();
        });

        $('.multi-event').on('click', '.deleteEventButton', function() {
                if ($('.multi-event', $wrapper).length > 1){
                $(this).parent('.multi-event').remove();
            }
        });
    });

 });

和.html:

<div class="eventsRowsWrapper">
    <div class="eventsRows sortable">
        <div class="form-group multi-event controls form-inline">
            <input name="date[]" maxlength="255" type="text" placeholder="Data" class="datepickerClass form-control sortable ui-sortable" size="20">
            <button type="button" style="float: none" class="close deleteEventButton">&times;</button>
        </div> 
    </div>

    <button class="btn btn-warning btn-sharp addEventButton" type="button" name="addEvent">
        <span class="glyphicon glyphicon-plus-sign"></span>Add event
    </button>
</div>

这是Fiddle

1 个答案:

答案 0 :(得分:2)

而不是:

$('.multi-event').on('click', '.deleteEventButton', function() {

写:

$(document).on('click', '.multi-event .deleteEventButton', function() {

您正在尝试在dom中不存在的内容上附加处理程序。