1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title>Document</title> 7 </head> 8 9 <body> 10 <input id='txt1' type="text"> 11 <input id='btn1' type="button" value="留言"> 12 <ul id="ul1"></ul> 13 <script> 14 window.onload = function() { 15 16 var oTxt = document.getElementById('txt1'); 17 var oBtn = document.getElementById('btn1'); 18 var oUl = document.getElementById('ul1'); 19 20 /** 21 22 document.createElement('標籤名'); 建立元素 23 24 父級.appendChild();添加元素 25 26 父級.insertBefore(新的元素,被插入的元素); 27 在ie下若是第二個參數表示的元素不存在,則會報錯 28 在其餘標準瀏覽器中,則會使用appendChild進行插入操做 29 30 父元素.replaceChild(新元素,舊元素);元素替換 31 32 */ 33 34 oBtn.onclick = function() { 35 var oLi = document.createElement('li'); 36 var oA = document.createElement('a'); 37 oA.innerHTML = '刪除'; 38 oA.href = 'javascript:;'; 39 oA.onclick = function() { 40 // 刪除當前行 41 this.parentNode.parentNode.removeChild(this.parentNode); 42 } 43 44 oLi.innerHTML = oTxt.value; 45 46 oTxt.value=''; 47 48 // 插入新建元素 49 oLi.appendChild(oA); 50 if (oUl.children.length >= 10) { 51 // 刪除最舊的數據 52 oUl.removeChild(oUl.children[oUl.children.length-1]); 53 } 54 // 添加子元素 55 addEle(oUl, oLi, oUl.children[0]); 56 }; 57 58 function addEle(obj, param1, param2) { 59 if (obj.children[0]) { 60 obj.insertBefore(param1, param2); 61 } else { 62 obj.appendChild(param1); 63 } 64 } 65 }; 66 </script> 67 </body> 68 69 </html>