Lev*_*sen 5 javascript html-table rows dynamic
我试图制作一个包含多行的表,每行的最后一个单元格中都有一个按钮,用于创建该行的副本。
所有其他单元格都包含输入(文本)。添加的输入的内容(值)必须与上面的内容(它们的副本之一)相同。
副本无法复制!
输入内容必须具有唯一的名称,例如:
1-1-name
1-1-age
1-1-country
1-1-email
如果复制了该行,则复制的输入必须具有这样
的名称:
1-2-2 名称1-2-age
1-2-国家
1-2-电子邮件
下一个用3代替2,依此类推。
我猜这是一个问题,我必须在没有JQuery的情况下执行此操作。我只能使用Javascript。这有可能吗?
看看这个小提琴。这是一个纯 js(非 jQuery)方法来复制表行并增加它的 ID:
\n\n\n\nvar idInit;\nvar table = document.getElementById(\'theTable\');\n table.addEventListener(\'click\', duplicateRow); // Make the table listen to "Click" events\n\nfunction duplicateRow(e){\n if(e.target.type == "button"){ // "If a button was clicked"\n var row = e.target.parentElement.parentElement; // Get the row\n var newRow = row.cloneNode(true); // Clone the row\n\n incrementId(newRow); // Increment the row\'s ID\n var cells = newRow.cells;\n for(var i = 0; i < cells.length; i++){\n incrementId(cells[i]); // Increment the cells\' IDs\n }\n insertAfter(row, newRow); // Insert the row at the right position\n idInit++;\n }\n}\n\nfunction incrementId(elem){\n idParts = elem.id.split(\'-\'); // Cut up the element\'s ID to get the second part.\n idInit ? idParts[1] = idInit + 1 : idInit = idParts[1]++; // Increment the ID, and set a temp variable to keep track of the id\'s.\n elem.id = idParts.join(\'-\'); // Set the new id to the element.\n}\n\nfunction insertAfter(after, newNode){\n after.parentNode.insertBefore(newNode, after.nextSibling);\n}\xe2\x80\x8b\nRun Code Online (Sandbox Code Playgroud)\n\n\n\n<table id="theTable">\n <tr id="1-1">\n <td id="1-1-name"><input type="text"/></td>\n <td id="1-1-age"><input type="text"/></td>\n <td id="1-1-country"><input type="text"/></td>\n <td id="1-1-email"><input type="text"/></td>\n <td id="1-1-button"><input type="button" value="Copy"/></td>\n </tr>\n</table>\xe2\x80\x8b\nRun Code Online (Sandbox Code Playgroud)\n\n编辑:更新为在单击的行之后插入新行。现在有按钮和输入!
\n