2016-10-10 155 views
0

這是我的JavaScript函數。如何使用JavaScript僅在tbody中添加數據

function SaveCustomdata() { 
    var customName = document.getElementById("lblNAME").value; 
    var customEmail = document.getElementById("lblEmail").value; 
    var customContectNo = document.getElementById("lblContectNO").value; 


    var row = ""; 
    row += '<tr><td>' + customName + '</td><td>' + customEmail + '</td><td>' + customContectNo + '</td></tr>'; 

    document.getElementById("Customdata").appendChild(row); 
} 

HTML代碼,我想數據

<table> 
    <thead> 
     <tr> 
      <th style=" color:#01A0DF; padding-right:60px;">Name</th> 
      <th style=" color:#01A0DF; padding-right:70px;">Email</th> 
      <th style=" color:#01A0DF; padding-right:90px;">Contect/Mobile No</th> 
      <td> 

       <input type="button" id="btnclick" value="Add" onclick="AddRecord()" /> 
      </td> 
     </tr> 
    </thead> 
    <tbody id="Customdata"></tbody> 
</table> 

追加獲得一個錯誤

0x800a139e - JavaScript run time error: Hierarchy Request Error 
+0

您需要的元素傳遞給'的appendChild()'不是一個字符串。 (使用'document.createElement(「tr」)'先創建一個,更新它,追加它) –

+0

你實際上必須用JS創建元素。你不能只使用jQuery來追加一個字符串。 http://www.w3schools.com/js/js_htmldom_nodes.asp – Gavin

+0

@Gavin http://www.w3fools.com/ –

回答

1

隨着使用innerHTML提到以編程方式做到這一點:

function SaveCustomdata() { 
    var customName = document.getElementById("lblNAME").value; 
    var customEmail = document.getElementById("lblEmail").value; 
    var customContectNo = document.getElementById("lblContectNO").value; 

    var row = ""; 
    row += '<tr><td>' + customName + '</td><td>' + customEmail + '</td><td>' + customContectNo + '</td></tr>'; 

    // get the current table body html as a string, and append the new row 
    var html = document.getElementById("Customdata").innerHTML + row; 

    // set the table body to the new html code 
    document.getElementById("Customdata").innerHTML = html; 
} 
0

這裏有一個fiddle。讓我們知道它是否對你有所幫助。
基本上你可以使用.innerHTML作爲元素附加字符串,因爲這會得到「瀏覽器評估」。

否則,你將不得不在評論

+0

感謝兄弟爲我工作。 –

相關問題