相關:
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、示例效果圖