0

我们正在使用以下代码创建一个可以通过按下按钮进行扩展的表单,但是我们在向输入字段添加唯一名称时遇到了麻烦。我们让它添加了一个唯一的 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
}
4

2 回答 2

1

您不再设置id属性,并且您现在是双增量counter并且name属性不适用于这种类型的Element,因此您必须专门获取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
}
于 2013-06-11T13:00:25.173 回答
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
于 2013-06-11T12:54:35.647 回答