在jquery中复制特定的html代码

Duplicate a specific html code in jquery

本文关键字:html 代码 jquery 复制      更新时间:2023-09-26

我有一个表,里面有一些复杂的值(我的意思是,我必须发出几个请求才能得到我想要的所有值)。我需要在这个表的末尾添加行,并用与现有html代码相同的代码填充单元格。

例如,我有这样的东西:

<table id="table_cultures">
    <tr>
        <td>Just a string</td>
        <td>Dropdown</td>
        <td><div class='foo'> something..</div></td>
    </tr>
</table>
<button id="plus_button" onclick="addRow()">+</button>

现在,在我的javascript中,我有这样的东西:

function addRow(){
    var table = document.getElementById("table_cultures"); //Get the table element
    var itk = document.getElementById('foo'); //Try to get the html to duplicate
    var row = table.insertRow(-1); //Add in the end of the table
    var c1 = row.insertCell(0);
    var c2 = row.insertCell(1);
    var c3 = row.insertCell(2);

        c1.innerHTML= 'Culture';
        c2.innerHTML='test';
        c3.innerHTML=itk;
}

因此,在变量itk中,我试图生成html并将其拉入单元格,bu[Object]t它只显示HTMLFormElement(因为这是一个我想要复制的表)。

这样做可能吗?或者还有其他更简单的方法吗?

您应该考虑克隆行节点,而不是通过以下方式获取和设置innerHTML:

 var table = document.getElementById("table_cultures"); //Get the table element
    var row = document.getElementById("rowTobeCloned"); //clone the required row
    var clone = row.cloneNode(true); // copy child nodes too
    table.appendChild(clone); // append the new row to the end of the table

目前您根本没有在代码中使用jQuery,但如果您正在寻找jQuery解决方案,您应该尝试.clone()

$("#table_cultures td:last").clone().appendTo("#table_cultures tr");

JSFiddle

您使用的是class("class='o'")而不是Id("getElementById")所以应该是像这个

function addRow(){...
var itk = document.getElementsByClassName('foo')[0]; //Try to get the html to duplicate
...}