2016-05-04 7 views
0

私はいくつかの複雑な値を持つテーブルを持っています(私はそれに必要なすべての値を取得するためにいくつかの要求をする必要があります)。私はこの表の最後に行を追加し、既存のhtmlコードと同じコードでセルを埋める必要があります。jqueryで特定のhtmlコードを複製する

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で、私が取得しようとしている:

<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ので、私のようなものを持っている:例えば

、私のようなものを持っています生成されたhtmlをセルに取り込み、オブジェクト[オブジェクト]にはHTMLFormElementと表示されます(これは複写したいテーブルなので)。

このようにすることは可能ですか?それとももっとシンプルな他の方法がありますか?

+0

'のdocument.getElementById( 'foo' で)innerHTML' –

+0

@MilindAnantwarあなたが意味する場合は、' c3.innerHTML =のdocument.getElementById( 'FOO')innerHTMLの;。。 '、/ – Erlaunis

+0

「innerHTML」は「innerHTML」である必要があります –

答えて

0

あなたは、行のノードを複製する代わりに、このようないくつかのことでinnerHTMLプロパティを取得および設定考慮しなければならない:あなたがすべてで、あなたのコード内でのjQueryを使用していない現時点では

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 
+0

「innerHTML」よりもこのメソッドを使用する理由を教えてください。 – Erlaunis

+0

単純に、ノードのクローン作成はhtmlの読み込みとリセットよりも高速です。これを確認してください:http://stackoverflow.com/questions/676249/deep-cloning-vs-setting-of-innerhtml-whats-faster –

0

が、あなたが探している場合あなたは、クラス( "クラス= 'foo' ではありません")ID( "getElementByIdを")01 .clone()

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

JSFiddle

0

使用してみてくださいjQueryのソリューションは、それはこのようなものでなければなりません

function addRow(){... 

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

...} 
関連する問題