動態地添加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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM