在点击表td输入每次追加相同的tr

时间:2015-05-04 10:04:01

标签: javascript jquery

当我点击td元素时,我在JavaScript中遇到了重复相同tr的问题。Here the image 我的HTML代码如下:

<table id="tabl2" class="table time-table table-bordered table-striped budrow">
<thead>
    <tr>
        <th class="cal-head">Rates</th>
        <th class="cal-head">Start date</th>
        <th class="cal-head">End date</th>
    </tr>
</thead>
<tr>
    <td>
        <input type="number" readonly placeholder="Rates">
    </td>
    <td>
        <input type="text" readonly id="start" placeholder="Start date">
    </td>
    <td>
        <input type="text" class="datepicker" name="enddate" placeholder="End date">
    </td>
</tr>

我试过这个js但失败了:

$('.budrow').click(function(){
   $(this).find('tr').append('<tr> <td></td> <td></td> <td></td> </tr>');
});

请帮帮我。

4 个答案:

答案 0 :(得分:1)

将click事件绑定到单击的元素,使用closest()选择当前行,然后使用after()函数追加新行:

&#13;
&#13;
$('.btn').on('click', function() {
  var that = $(this);
  var newRow = '<tr><td colspan="3">This is a new row</td></tr>';
  that.closest('tr').after(newRow);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td>
        <button class="btn">click</button>
      </td>
      <td>
        <button class="btn">click</button>
      </td>
      <td>
        <button class="btn">click</button>
      </td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以克隆并添加新行,也最好单独使用添加按钮

<button class="budrow">Add</button>
<table id="tabl2" class="table time-table table-bordered table-striped budrow">
    <thead>
        <tr>
            <th class="cal-head">Rates</th>
            <th class="cal-head">Start date</th>
            <th class="cal-head">End date</th>
        </tr>
    </thead>
    <tr>
        <td>
            <input type="number" readonly placeholder="Rates" />
        </td>
        <td>
            <input type="text" readonly id="start" placeholder="Start date" />
        </td>
        <td>
            <input type="text" class="datepicker" name="enddate" placeholder="End date" />
        </td>
    </tr>
</table>

然后

jQuery(function ($) {
    var $tr = $('#tabl2 tbody tr').eq(0);
    $('button.budrow').click(function () {
        var $clone = $tr.clone();
        $('#tabl2').append($clone);
        $clone.find('.datepicker').removeClass('hasDatepicker').datepicker();
    });
    $('.datepicker').datepicker();
});

演示:Fiddle

答案 2 :(得分:1)

尝试使用:

var $table = $('#tabl2');
$table.click(function(e){
   var $tr = $(e.target).closest('tr');
   if (($tr.parent().prop("tagName") != 'THEAD') && $tr.is(":last-child"))
       $tr.after($tr.clone());
});

JSFiddle

答案 3 :(得分:0)

    $('.budrow tbody input').click(function(e){
        makeClone(e);
    });

    function makeClone(e){
        var newClone = $(e.target).closest("tr").clone();
        $("#tabl2 tbody").append(newClone);
        $(newClone).click(function(ev){
            makeClone(ev);
        })
    }