javascript
  • jquery
  • html
  • 2016-05-04 27 views 0 likes 
    0

    我有一個表有一些複雜的值(我的意思是我必須提出幾個請求來獲取我想要的所有值)。我需要在該表的末尾添加行,並使用與現有html代碼相同的代碼填充單元格。在jquery中複製一個特定的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並將其拉入單元格中,但它僅顯示HTMLFormElement(因爲它是我想要複製的表格)。

    這樣做有可能嗎?或者有其他更簡單的方法嗎?

    +0

    '的document.getElementById( '富')innerHTML' –

    +0

    @MilindAnantwar如果你的意思'c3.innerHTML =的document.getElementById( '富')的innerHTML;'它不起作用,它說「未定義」:/ – Erlaunis

    +0

    'innerHtml'應該是'innerHTML' –

    回答

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

    你能解釋一下爲什麼我應該使用這種方法而不是「innerHTML」? – Erlaunis

    +0

    簡而言之,因爲克隆節點比讀取和重置html更快。請檢查此:http://stackoverflow.com/questions/676249/deep-cloning-vs-setting-of-innerhtml-whats-faster –

    0

    在你是不是在你的代碼使用jQuery在所有的時刻,但如果你正在尋找jQuery的解決方案,你應該嘗試.clone()

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

    JSFiddle

    0

    您使用類( 「類= '富'」)未ID( 「的getElementById」) 所以它應該是這樣的

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