>我正在尝试制作一个包含几行的表格,每行在最后一个单元格中都有一个按钮,用于创建该行的副本。
所有其他单元格都包含输入(文本)。添加的输入的内容(值)必须与上面的内容(它们是副本的内容)相同。
但是,副本无法复制!
输入必须具有唯一的名称,如下所示:
1-1-名称
1-1岁
1-1-国家
1-1-电子邮件
如果复制此行,则复制的输入必须具有这样的
名称1-2-名称
1-2岁
1-2个国家
1-2-电子邮件
下一个是 3 而不是 2,依此类推。
我想,这样做
的问题是,我必须在没有JQuery的情况下做到这一点。我只能使用Javascript。这可能吗?
看看这个小提琴。这是一种纯 js(no-jQuery)方法来复制表行并增加其 ID:
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>
编辑:更新为在单击的行之后插入新行。现在有了按钮和输入!
是的,这是可能的,你应该创建一个新的表行,然后将其内部HTML设置为上面行的内部HTML。
jQuery是一个JavaScript库,这意味着它是用JavaScript函数构建的。
所以你可以用jQuery做的一切,你也可以用JavaScript做。
莱昂