动态地添加HTML控件-JavaScript基础

相关:

document对象的createElement()方法可以创建一个新的HTML控件(document.createElement("input");)

setAttribute()方法设置控件类型、设置控件的名称(otext.setAttribute("type","text");otext.setAttribute("name","username");)。

appendChild()方法将新的HTML控件插入到相应的元素的最后一个子节点后面( document.form.appendChild(obtn);)。

 document.form.innerHTML = ""; 将内容设为空

1、示例代码

<!DOCYTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>动态添加html控件</title>
<style>
body{font-size: 12px}
.button{background-color: #03a9f4;color: white}
</style>
</head>
<body>
<form name="form">
  <input type="button" class="button" value="添加文本框" onclick="addText()">
  <input type="button" class="button" value="添加按钮" onclick="addBtn()">
  <input type="button" class="button" value="删除所有控件" onclick="delElement()">
  <br><br>用户名:
</form>
</body>
<script>
function addText() {
  var otext = document.createElement("input");//创建input控件
  otext.setAttribute("type","text");//设置控件类型
  otext.setAttribute("name","username");//设置控件名称
  document.form.appendChild(otext);//将控件添加到form节点子节点后面
}
function addBtn() {
  var obtn = document.createElement("input");
  obtn.type = "button";//设置类型为button
  obtn.value = "确定";//设置控件显示的文字
  document.form.appendChild(obtn);//将控件添加到form节点子节点后面

}
function delElement() {
  document.form.innerHTML = "";//清空了所在页面
}
</script>
</html>

2、示例效果图

源码下载:动态添加HTML控件.zip

原文地址:https://www.cnblogs.com/qikeyishu/p/7603549.html