簡體   English   中英

在javascript中,如何使用document.createElement()在表中添加新行?

[英]In javascript, how to add new rows in a table using document.createElement()?

我想要一個表和一個文本框,當我為文本框輸入一些值然后單擊按鈕時,該值將添加到表中。 我寫了代碼,但是沒有運行。 請幫助我找出下面的代碼有什么問題。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script>
function send() {
        tbl=document.getElementById("idtable");
        tr = document.createElement("tr");
        td1 = document.createElement("td");
        td2 = document.createElement("td");
        name = document.getElementById("txtname").value;
        email = document.getElementById("txtemail").value;
        td1.innerText=name;
        td2.innerText=email;
        tr.appendChild(td1);
        tr.appendChild(td2);
        tbl.appendChild(tr);
}
</script>
</head>
<body>
<input type="text" id="txtname" name="txtname"/> <br/><br/>
<input type="text" id="txtemail" name="txtemail"/>
<p> <input type="button" value="Send" onclick="send()"/>
<table id="idtable" border="1">
<tr><td>Name</td> 
 <td>Email</td>
</tr>
</table>
</body>
</html>

試試這個代碼:

 function send(){ var table=document.getElementById("table"); name=document.getElementById("txtname").value; email=document.getElementById("txtemail").value; table.innerHTML+=('<tr><td>'+name+'</td><td>'+email+'</td></tr>') } 
 <input id="txtname" name="txtname"/> <br/> <input id="txtemail" name="txtemail"/> <br/> <input type="button" value="Send" onclick="send()"/><br/> <table id="table" border="1"> <tr><td>Name</td><td>Email</td></tr> </table> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM