jquery删除最后一个td的内容

时间:2013-09-24 06:35:32

标签: jquery

我有一张桌子$(“#Customers”)。

<table id="Customers">
 <tbody>
  <tr>
    <td>
        <input id="model_0_name" type="text" name="model[0].name"/>              
    </td>
    <td>
        <button>Add</button>
    </td>
  </tr>
 </tbody>
</table>

每行在最后一个td元素中都有一个按钮。我想克隆该行并将其添加到单击的行下方。我想从克隆行中删除按钮元素。克隆部分正在运行,但按钮未被删除。此外,我想将新输入行的id和名称重命名为新索引:例如:model [1] .name。

 $("#Customers > tbody > tr").click(function (event) {
        event.preventDefault();
        // get row index
        var rowndx = $("tr").index(this);
        var cnt = $("#Customers > tbody > tr").length;
        var clonerow = $(this)
            .clone()
            .wrap("<tr></tr>").parent().html();
        $("#Customers > tbody > tr").eq(rowndx - 1).after(clonerow).remove("tr > td:last");          
    });

4 个答案:

答案 0 :(得分:0)

您应该尝试从克隆对象中删除:

var clonerow = $(this)
    .clone().find("td:last").remove().end()
    .wrap("<tr></tr>").parent().html();

Here is working Demo

答案 1 :(得分:0)

你可以这样做:

..
var clonerow = $(this)
            .clone().find("button").remove().end()
            .wrap("<tr></tr>").parent().html();

演示:: jsFiddle

工作代码:

$("#Customers > tbody > tr").click(function (event) {
   event.preventDefault();
   // get row index
   var rowndx = $("tr").index(this);
   var cnt = $("#Customers > tbody > tr").length;
   var clonerow = $(this)
            .clone().find("input").attr("id", "model_"+cnt+"_name").end().find("button").remove().end()
            .wrap("<tr></tr>").parent().html();
   $("#Customers > tbody > tr").eq(rowndx - 1).after(clonerow);          
});

更新了Fiddle

答案 2 :(得分:0)

我添加了点击事件以添加按钮..因为选择器为<tr>,关注输入将最终添加新的<tr>

试试这个

$("#Customers > tbody > tr > td > button").click(function (event) {
  event.preventDefault();
  // get row index
  var $tr = $(this).parents('tr'); //get parent `tr`
  var countTR = $("#Customers tr").length //get total length of tr
  var cloned = $tr.clone(); //clone it
  cloned.find('td:last').remove(); //remove the last td from cloned element
  cloned.find('input').val('').attr('name', 'model' + [countTR + 1] + '.name') //find inout chnage name and empty the calue
  $("#Customers tr:last").after(cloned); //append it at the end
});

fiddle here

答案 3 :(得分:0)

试试这段代码:

$("#Customers > tbody > tr > td > button").on('click', function() {
    var $tr    = $(this).closest('tr');
    var $clone = $tr.clone();
    $clone.find('td:last').remove();
    $tr.after($clone);
});

Fiddle Demo Here

相关问题