我正在运行w3schools的代码,动态地向页面添加按钮。这是代码。
<!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>
但是当我有<form>
标记时,这种动态添加不起作用。我可以使用JavaScript进行哪些更改以适应动态按钮,而无需删除<form>
标记?
答案 0 :(得分:1)
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>