0

最初の行を削除しようとすると機能しますが、行を追加すると削除できません。何らかの理由で、最初の行しか削除できません。

ここに私のhtmlがあります

<table class="pretty property_units" style="width:800px;">
<thead>
<tr>
<th>Bedroom</th>
<th>Bathroom</th>
<th>Square Feet</th>
<th>Price</th>
<th>Available</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr class="rows">
    <td><input type='text' name='bedroom[]' value='0' class='input-small'></td>
    <td><input type='text' name='bath[]' value='0' class='input-small'></td>
    <td><input type='text' name='sqrt[]' value='0' class='input-small'></td>
    <td><input type='text' name='price[]' value='0' class='input-small'></td>
    <td>
        <select name='avail[]' class='input-small'>
        <option value='yes'>Yes</option>
        <option value='no'>No</option>
        </select>
    </td>
    <td><button type="button" class="btn btn-danger btn-small removeRow">remove</button></td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-small btn-primary addrow">add row</button>

ここに私のjsがあります

<script type="text/javascript">
$(document).ready(function() {
    $(".addrow").click(function() {
        var tblrow = $('table.property_units tr.rows:last').clone();
        $("table.property_units tbody").append(tblrow);
    });

    $(".removeRow").click(function() {
        $(this).closest("tr").remove();
        return false;
    });
});
</script>
4

3 に答える 3

2

イベントを委任する必要があります。

$(document).on('click', '.removeRow', function() {
    $(this).closest("tr").remove();
    return false;
});

パフォーマンスを向上させるために、テーブルに id を追加し、イベントを の代わりにテーブルにバインドしますdocument

詳細については、この質問をご覧ください。

于 2013-08-24T21:48:32.750 に答える
0

jQuery で新しい要素を作成するときは、イベントをバインドする必要があります。代わりにデリゲートを使用できますクリックして、ここを確認してください: ここ にリンクの説明を入力してください

または、関数 deleteRws(){ delete のコード} を作成し、次の後に呼び出すことができます: $("table.property_units tbody").append(tblrow);

于 2013-08-24T21:47:40.990 に答える
0

これ$(".removeRow").click(...は、呼び出された時点で存在していた一致する行にのみ適用されます。.addrowクリック ハンドラーを介して作成された新しい行 (およびその内容) には影響しません。

手動で追加する必要があります:

$(document).ready(function() {
  var remover = function() {
    $(this).closest("tr").remove();
    return false;
  };

  $(".addrow").click(function() {
          var tblrow = $('table.property_units tr.rows:last').clone();
          $('.removeRow', tblrow).click(remover);
          $("table.property_units tbody").append(tblrow);
      });

  $(".removeRow").click(remover);
});

例: http://codepen.io/paulroub/pen/Bekit

于 2013-08-24T21:48:59.667 に答える