添加事件侦听器以触发相同的功能以动态创建按钮

时间:2016-06-09 16:10:26

标签: javascript jquery html

我有这个jquery代码,

 var next = 1;
$(".add-more").click(function(e){
    e.preventDefault();
    $(this).replaceWith("<button id='remove" + (next) + "' class='btn btn-danger remove-me pull-right'>-</button>");
    var addto = "#field" + next;
    next = next + 1;
    var str = "<tr id='field" + next + "'><td><input autocomplete='off' class='input form-control' id='item" + next + "' name='item" + next + "' type='text' data-items='8'/></td>"+
                "<td><input autocomplete='off' class='input form-control' id='desc" + next + "' name='desc" + next + "' type='text' data-items='8'/></td>"+
                "<td><input autocomplete='off' class='input form-control' id='qty" + next + "' name='qty" + next + "' type='text' data-items='8'/></td>"+
                "<td><input autocomplete='off' class='input form-control' id='ucost" + next + "' name='ucost" + next + "' type='text' data-items='8'/></td>"+
                "<td><input autocomplete='off' class='input form-control' id='tcost" + next + "' name='tcost" + next + "' type='text' data-items='8'/></td>"+
                "<td><input autocomplete='off' class='input form-control' id='type" + next + "' name='type" + next + "' type='text' data-items='8'/></td>"+
                "<td><button id='b1' class='btn add-more pull-right' type='button'>+</button></td></tr>";
    $(addto).after(str);
    $("#count").val(next); 
    $('.remove-me').click(function(e){
            e.preventDefault();
            var fieldNum = this.id.charAt(this.id.length-1);
            var fieldID = "#field" + fieldNum;
            $(this).remove();
            $(fieldID).remove();
    });
});

这行代码使用户能够创建多个字段。 如果用户单击&#34;添加&#34;按钮,它将创建多个字段。 这也将改变&#34;添加&#34;按钮到&#34;删除&#34;按钮。并添加另一个&#34;添加&#34;按钮。

我的问题是,动态创建的#b1按钮没有事件监听器。

我尝试使用这行代码,

$("#field" + next).attr('data-source',$(addto).attr('data-source'));

但它不起作用。我的想法就像这个,

http://bootsnipp.com/snippets/featured/dynamic-form-fields-add-amp-remove

任何人都可以帮助我?

1 个答案:

答案 0 :(得分:0)

用于动态创建的元素使用

$(document).on('click', '.add-more', function() {...};

而不是

$('.add-more').click(...

这称为事件委托,您将事件添加到文档(或父元素,它从页面加载中存在),然后在其子项时触发,您指定为参数(在本例中为'.add-more')点击

相关问题