简体   繁体   English

document.body.appendChild() 不工作<form>

[英]document.body.appendChild() not working with <form>

I am running the code from w3schools to add button dynamically to the page.我正在运行 w3schools 的代码以动态地向页面添加按钮。 Here is the code.这是代码。

 <!DOCTYPE html> <html> <body> <p>Click the button to make a BUTTON element with text.</p> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var btn = document.createElement("BUTTON"); var t = document.createTextNode("CLICK ME"); btn.appendChild(t); document.body.appendChild(btn); } </script> </body> </html>

But this dynamic addition doesn't work when I have a <form> tag.但是当我有一个<form>标签时,这个动态添加不起作用。 What changes in the JavaScript I can make to accommodate dynamic button without having to remove the <form> tag?我可以对 JavaScript 进行哪些更改以适应动态按钮而无需删除<form>标记?

 function myFunction() { var btn = document.createElement("BUTTON"); var t = document.createTextNode("CLICK ME"); btn.appendChild(t); document.getElementById('theForm').appendChild(btn); } </script>
 <p>Click the button to make a BUTTON element with text.</p> <button onclick="myFunction()">Try it</button> <form id="theForm"> </form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM