为克隆的表单元素添加唯一名称

时间:2013-06-11 12:48:06

标签: javascript appendchild clonenode

我们使用以下代码创建一个可以通过按下按钮进行扩展的表单,但是我们无法在输入字段中添加唯一名称。我们让它工作添加一个唯一的ID,但是当我们将其更改为名称时它停止工作。救命? :(非常感谢任何建议。

var counter = 0
function cloneRow() {
   counter ++;      
   var row = document.getElementById("rowToClone"); // find row to copy
   var table = document.getElementById("tableToModify"); // find table to append to
   var clone = row.cloneNode(true); // copy children too
   var theName= row.name;
   clone.name = theName + counter++; // change id or other attributes/contents
   table.appendChild(clone); // add new row to end of table
}

2 个答案:

答案 0 :(得分:1)

试试这个: -

var clone = row.cloneNode(true); // copy children too

    var theName= row.getAttribute('name');

    clone.setAttribute('name', theName + counter++);// change id or other attributes/contents

答案 1 :(得分:1)

您不再设置 id 属性,现在您正在加倍counter,而name property不适用于此类{ {3}},所以你必须具体Element。请参阅此get the attribute

  

name获取或设置DOM对象的name属性,它仅适用于以下元素:<a>, <applet>, <button>, <form>, <frame>, <iframe>, <img>, <input>, <map>, <meta>, <object>, <param>, <select>,<textarea>.

var counter = 0;

function cloneRow() {
    var row = document.getElementById("rowToClone"),      // row to copy
        table = document.getElementById("tableToModify"), // table to append to
        clone = row.cloneNode(true),                      // clone with children
        theName = row.getAttribute('name') + ++counter;   // get name attribute
        // inc counter there, too

    clone.setAttribute('name', theName); // re-set name
    clone.setAttribute('id', theName);   // set ID (lost during clone)
    table.appendChild(clone);            // add new row to end of table
}