我有一个表,我有一个按钮,然后当我点击那个按钮,我插入一个新的行。但是在插入一行之后,我不能再插入另一行。
有关更多间隙,请参见fiddle
HTML格式:

<table id="sales-journal">
    <tbody>
        <tr class="sales-journal-row">
            <td class="grid-40">
                <select id="sales-product-id" name="sales-product-id" required="required">
                    <option value="1">Option 1</option>
                    <option value="2">Option 2</option>
                    <option value="3">Option 3</option>
                </select>
            </td>
            <td class="grid-20">
                <input type="number" step="1" id="sales-sold-qty" name="sales-sold-qty" />
            </td>
            <td class="grid-20">
                <input type="number" step="1" id="sales-spill-qty" name="sales-spill-qty" />
            </td>
            <td class="grid-20">
                <button class="sales-journal-add" id="1" />Add Product</button>
            </td>
        </tr>
    </tbody>
</table>

JS公司:
var cur_id = $(".sales-journal-add").attr('id');
var next_id = parseInt(cur_id) + 1;

$("#" +cur_id).click(function() {
    var clone = $('#sales-journal > tbody:last').clone();
    clone.insertAfter('#sales-journal > tbody:last');
    $(this).attr('disabled', 'disabled').addClass('disabled');
    alert(cur_id);
    clone.find('.sales-journal-add:last').attr('id', next_id);
    cur_id = next_id;
});

$("#" +next_id).click(function() {
    alert("lepa");

    var clone = $('#sales-journal > tbody:last').clone();
    clone.insertAfter('#sales-journal > tbody:last');
    $(this).attr('disabled', 'disabled').addClass('disabled');

    clone.find('.sales-journal-add:last').attr('id', next_id);
});

最佳答案

Use event delegation-

$('#sales-journal').on('click','.sales-journal-add', function () {
    var clone = $('#sales-journal > tbody:last').clone();
    clone.insertAfter('#sales-journal > tbody:last');
    $(this).attr('disabled', 'disabled').addClass('disabled');
    alert(cur_id);
    clone.find('.sales-journal-add:last').attr('id', next_id);
    cur_id = next_id;
});


$('#sales-journal').on('click','.sales-journal-add', function () {
    alert("lepa");

    var clone = $('#sales-journal > tbody:last').clone();
    clone.insertAfter('#sales-journal > tbody:last');
    $(this).attr('disabled', 'disabled').addClass('disabled');

    clone.find('.sales-journal-add:last').attr('id', next_id);
});

Demo--->http://jsfiddle.net/g2UwK/5/
http://learn.jquery.com/events/event-delegation/

09-25 18:12