我正在尝试制作一个包含多行的表格,每行在最后一个单元格中都有一个按钮,用于创建该行的副本。
所有其他单元格都包含一个输入(文本)。 添加的输入的内容(值)必须与上面的相同(它们是副本)。
但是无法复制副本!
输入必须有一个像这样的唯一名称:
1-1-名字
1-1岁
1-1国
1-1-电子邮件
如果这一行被复制,复制的输入必须有这样的名字
1-2-名字
1-2岁
1-2国
1-2-电子邮件
下一个是 3 而不是 2,依此类推。
我想,问题在于我必须在没有 JQuery 的情况下执行此操作。我只能使用 Javascript。这可能吗?
最佳答案
看看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>
编辑:更新为在单击的行之后插入新行。现在有了按钮和输入!
关于javascript - 如何使用 Javascript 创建一个包含可以复制的行的表(在该行之后添加一个新行,包含相同的行)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13764140/