在jquery

时间:2016-05-04 08:28:05

标签: javascript jquery html

我有一个包含一些复杂值的表(我的意思是我必须提出几个请求来获取我想要的所有值)。我需要在此表的末尾添加行,并使用与现有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]它只显示HTMLFormElement(因为它是我要复制的表)

那可能这样做吗?或者还有另外一种更简单的方法吗?

3 个答案:

答案 0 :(得分:0)

您应该考虑克隆行节点,而不是使用以下内容获取和设置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

答案 1 :(得分:0)

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

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

JSFiddle

答案 2 :(得分:0)

您使用的是课程(&#34; class =&#39; foo&#39;&#34;)而不是ID(&#34; getElementById&#34;) 所以它应该是这样的

function addRow(){...

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

...}