createElement()結合appendChild()的執行個體

來源:互聯網
上載者:User

標籤:

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()的執行個體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.