【问题标题】:How to make a table with rows that can be copied (adding a new row after that one, containing the same) with Javascript?如何使用 Javascript 制作一个包含可复制行的表(在该行之后添加一个新行,包含相同的行)?
【发布时间】:2012-11-25 16:38:42
【问题描述】:

我正在尝试制作一个包含多行的表格,每行在最后一个单元格中都有一个按钮,用于创建该行的副本。

所有其他单元格都包含一个输入(文本)。 添加的输入的内容(值)必须与上面的相同(它们是它们的副本)。

但是无法复制副本!


输入必须具有唯一的名称,如下所示:
1-1-姓名
1-1-年龄
1-1-国家
1-1-电子邮件

如果此行被复制,则复制的输入必须具有这样的名称
1-2-姓名
1-2岁
1-2-国家
1-2-电子邮件

下一个是 3 而不是 2,以此类推。


我想,这个问题是我必须在没有 JQuery 的情况下这样做。我只能使用 Javascript。这甚至可能吗?

【问题讨论】:

  • 这不是真正的重复,因为我希望副本出现在原始之后,而不是在表格的末尾。
  • ID 没有排序有关系吗?
  • 不,这没关系。重要的是它们出现在被点击的那个之后。 ;)

标签: javascript dynamic html-table rows


【解决方案1】:

看看this fiddle。这是一种复制表格行并增加其 ID 的纯 js(非 jQuery)方法:

var idInit;
var table = document.getElementById('theTable');
    table.addEventListener('click', duplicateRow);  // Make the table listen to "Click" events

function duplicateRow(e){
    if(e.target.type == "button"){ // "If a button was clicked"
        var row = e.target.parentElement.parentElement; // Get the row
        var newRow = row.cloneNode(true); // Clone the row

        incrementId(newRow); // Increment the row's ID
        var cells = newRow.cells;
        for(var i = 0; i < cells.length; i++){
            incrementId(cells[i]); // Increment the cells' IDs
        }
        insertAfter(row, newRow); // Insert the row at the right position
        idInit++;
    }
}

function incrementId(elem){
    idParts = elem.id.split('-'); // Cut up the element's ID to get the second part.
    idInit ? idParts[1] = idInit + 1 : idInit = idParts[1]++;  // Increment the ID, and set a temp variable to keep track of the id's.
    elem.id = idParts.join('-'); // Set the new id to the element.
}

function insertAfter(after, newNode){
    after.parentNode.insertBefore(newNode, after.nextSibling);
}​
<table id="theTable">
    <tr id="1-1">
        <td id="1-1-name"><input type="text"/></td>
        <td id="1-1-age"><input type="text"/></td>
        <td id="1-1-country"><input type="text"/></td>
        <td id="1-1-email"><input type="text"/></td>
        <td id="1-1-button"><input type="button" value="Copy"/></td>
    </tr>
</table>​

编辑:已更新以在单击的行之后插入新行。现在有了按钮和输入!

【讨论】:

  • 这正是我所需要的 :D 谢谢!!
  • 这在我的工作电脑上不起作用(使用旧版本的 IE)。所以我将第三行添加到评论中://table.addEventListener('click', duplicateRow); 我将其添加到按钮输入中:onClick="duplicateRow(event);"
  • 那么我建议将其添加到表格中。出于效率/内存使用的原因,您通常需要尽可能少的事件侦听器。
【解决方案2】:

是的,这是可能的, 你应该创建一个新的表格行, 然后将其innerHTML 设置为上一行的innerHTML。

jQuery 是一个 JavaScript 库,这意味着它是用 JavaScript 函数构建的。

所以一切你可以用 jQuery 做,你也可以用 JavaScript 做。

莱昂

【讨论】:

  • 如果可以防止,请不要使用innerHTML
  • 为什么 innerHTMl 是个坏主意?
  • 使用innerHTML 会强制浏览器重新解析DOM,因为浏览器无法预测添加了什么样的元素。 (在DOM操作时,浏览器可以)
  • 我不知道,为你 +1。
猜你喜欢
  • 2022-09-08
  • 2017-08-08
  • 1970-01-01
  • 2017-04-29
  • 2011-08-02
  • 1970-01-01
  • 1970-01-01
  • 2020-08-09
  • 2018-07-04
相关资源
最近更新 更多