简体   繁体   English

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

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

I want to have a table and a textbox, when I input some value for the textbox then click the button, the value will be added into a table. 我想要一个表和一个文本框,当我为文本框输入一些值然后单击按钮时,该值将添加到表中。 I wrote the code but it doesn't run. 我写了代码,但是没有运行。 Please help me to find out what wrong with the code below. 请帮助我找出下面的代码有什么问题。

<!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>

try this code: 试试这个代码:

 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