標籤:
createElement()作用是在JavaScript中建立一個元素
appendChild()向html元素添加節點
下面是衝浪後改編的例子代碼
先插html代碼
<body><ul><li value="1">載入按鈕</li><li value="2">載入下拉框</li><li value="3">載入文字框</li></ul><div id = "show">例子將在這裡進行展示</div></body>
1 <script> 2 window.onload = function(){ 3 4 var show = document.getElementById("show"); 5 var ul = document.getElementsByTagName("ul")[0]; 6 var li = ul.childNodes; 7 for(var i=0; i<li.length; i++){ 8 li[i].onclick = function() { 9 if(show.childNodes.length > 0){//判斷show裡面有沒有東西10 show.removeChild(show.childNodes[0]);//如果有就刪掉,完成初始化11 //show.innerHTML = ‘‘;//這樣也能直接刪除show的子節點,更方便12 } 13 selectFunction(parseInt(this.getAttribute("value")));//value值是字串,需要用parseInt()轉換成數字,然後傳值14 }15 }16 function selectFunction(index){//接收參數並調用相應的函數17 switch(index){18 case 1:createInput();19 break;20 case 2:createSelect();21 break;22 case 3:createText();23 24 }25 }26 function createInput() {27 // show.removeChild(show.childNodes[0]);28 var e = document.createElement("input");29 e.type = "button";30 e.value = "這是載入測試的小例子";31 show.appendChild(e); 32 }33 function createSelect(){34 35 var e = document.createElement("select");36 e.options[0] = new Option("附加元件1","");37 e.options[1] = new Option("附加元件2","");38 show.appendChild(e);39 }40 function createText(){41 var e = document.createElement("input");42 e.setAttribute("name","q");43 e.setAttribute("value","使用setAttribute");44 e.setAttribute("type","text");//使用setAttribute和e.type="text";效果是一樣的,但setAtt是1級dom,相容性更好45 show.appendChild(e);46 }47 }48 </script>
這是效果
效果:http://lingwer111.go4.arebz.co/createElement.html
createElement()結合appendChild()的執行個體