当多个按钮具有相同 class 时,preventDefault 不起作用

preventDefault not working when multiple buttons with the same class

我有一个按钮可以将一些表单元素附加到 div。问题是,按钮在追加时也被复制了。第一次单击 "add" 按钮时,将添加另一行表单元素。当我单击第一次单击添加的 "add" 按钮(添加另一行)时,页面刷新(preventDefault 不起作用)。删除按钮有效,但我只能添加一行。我想在每一行都有 "add" 按钮,但不确定如何实现。

代码如下:

<form class="form-inline" role="form">
    <div class="butter">
        <div class="form-group">
            <label class="sr-only" for="exampleInputEmail2">Email</label>
            <input type="email" class="form-control" id="exampleInputEmail2" placeholder="Email">
        </div>
        <div class="form-group">
            <label class="sr-only" for="exampleInputPassword2">Password</label>
            <input type="password" class="form-control" id="exampleInputPassword2" placeholder="Password">
        </div>
        <button class="btn btn-info nutter">add</button>
    </div>
</form>

<script id="add_form">
    <div class="spacer">
        <div class="form-group">
            <label class="sr-only" for="exampleInputEmail2">Email</label>
            <input type="email" class="form-control" id="exampleInputEmail2" placeholder="Email">
        </div>
        <div class="form-group">
            <label class="sr-only" for="exampleInputPassword2">Password</label>
            <input type="password" class="form-control" id="exampleInputPassword2" placeholder="Password">
        </div>
        <button class="btn btn-info nutter">add</button>
        <button class="btn btn-danger gutter">remove</button>
    </div>
</script>

$(document).ready(function() {
    var wrapper         = $('.butter'); //Fields wrapper
    var add_button      = $('.nutter'); //Add button ID

    $(add_button).click(function( e ) { //on add input button click
        e.preventDefault();
        var text = $('#add_form').html();
        $(wrapper).append(text); //add input box
    });

    $(wrapper).on("click",".gutter", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});

这是 jsfiddle:http://jsfiddle.net/7o1rgsw3/1

由于您是在每次点击时动态添加 html,因此您需要使用 on 方法而不是 click

$(document).ready(function() {
    $(document).on('click', '.nutter',function(e) { 
        e.preventDefault();
        var text = $('#add_form').html();
        $('.butter').append(text);
    });

     $(document).on("click",".gutter", function(e){ //user click on remove text
        e.preventDefault(); 
        $(e.target).closest('.spacer').remove();
    });
});

here is the fiddle