首页 文章

如何使用Javascript创建一个包含可以复制的行的表(在该行之后添加一行,包含相同的新行)?

提问于
浏览
3

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

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

但是副本无法复制!


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

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

下一个用3而不是2,依此类推 .


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

2 回答

  • 4

    看看this fiddle . 这是一个复制表行并增加它的ID的纯js(no-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>​
    

    Edit: 已更新以在单击后插入新行 . 现在有按钮和输入!

  • 0

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

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

    所以你可以用jQuery做的一切,你也可以使用JavaScript .

    莱昂

相关问题