使用附加复制表行 - 想创建唯一ID

时间:2010-08-17 14:07:27

标签: jquery

我有一个表单,其中包含一个包含项目行的表供用户填写  in。我目前设置它,以便用户可以添加额外的  他们需要添加更多信息的行。

这非常有效,但我想知道是否有办法生成  每个克隆字段的唯一ID。

My function is currently this:

 function addTableRow(table) {
         $(table).append($(table + ' tr:last').clone());
         return true;
   }

并从onclick中传入表id。

表格行包含以下信息:

<tr>
     <td><input type="text" id="txtBarnParts1" name="txtBarnParts
 []"></td>
     <td><input type="text" id="txtBarnWidth1" name="txtBarnWidth
 []">ft</td>
     <td><input type="text" id="txtBarnRemarks1"
 name="txtBarnRemarks1[]"></td>
</tr>

当我克隆id的行时,我想要的是什么  增加1,以便下一行有id:

txtBarnParts2,txtBarnWidth2,txtBarnRemarks2 ......等等。

有办法做到这一点吗?

谢谢!

4 个答案:

答案 0 :(得分:4)

var $newTr = $(table + ' tr:last').clone();
var newIndex = $newTr.index() + 1;
$newTr.find('[id]').each(function () {
    this.id = this.id.replace(/[0-9]+$/e, newIndex);
});
$(table).append($newTr);

答案 1 :(得分:2)

试试这个。需要jQuery 1.4或更高版本。

根据您的使用情况,我假设table存储带有哈希值的ID,如"#myTable"中所示。

function addTableRow(table) {
   var $last = $(table + ' tr:last');
   var num = $last.index() + 1; // If the IDs in each row are indexed starting
                                //    with 1, then you would need "+ 2" instead
   $last.clone().find(':input[id]')
         .attr('id', function(i,current) { 
                         return current.replace(/\d+$/, num);
                    })
         .end().appendTo(table);
   return true;
}

这会在新(克隆)行上执行.find(),搜索具有ID属性的input元素。然后它将函数传递给.attr()方法,该方法用新的数字替换当前的结束数字。


编辑:错过了.attr()来电中的逗号。固定的。

编辑:.clone()出错。固定的。

答案 2 :(得分:0)

var i = 1
function addTableRow() {
         $("table").append($("table tr:last").clone());
         $("table tr:last input").attr("name", $("table tr:first input").attr("name")+i);
         i++;
   })

这与姓名一起使用。类似的也适用于id。

答案 3 :(得分:0)

这是通用功能

    var indexCloneTableLastRowSelect = 1;
    var indexCloneTableLastRowInput = 1;
    var forEachElementItrateOnce = 1;
function cloneTableLastRow_(tableID_) {


    tableID_ = '#' + tableID_;
    // copy|clone last row 
    $(tableID_).append($(tableID_ + " tr:last").clone());
    $(tableID_ + " tr:last").each(function (){

        $(tableID_ + " tr:last select").attr("name", function() {
            if (forEachElementItrateOnce == 1){
                indexCloneTableLastRowSelect++;
            }            
            this.name = this.name.replace(/[0-9]+$/, indexCloneTableLastRowSelect);
            this.id = this.id.replace(/[0-9]+$/, indexCloneTableLastRowSelect);
            forEachElementItrateOnce = 0;
        })
        $(tableID_ + " tr:last input").attr("name", function() {
            if (forEachElementItrateOnce == 1){
                indexCloneTableLastRowInput++;
            }
            this.name = this.name.replace(/[0-9]+$/, indexCloneTableLastRowInput);
            this.id = this.id.replace(/[0-9]+$/, indexCloneTableLastRowInput);
            forEachElementItrateOnce = 0;
        })

    })
    forEachElementItrateOnce = 1;
}