用DOM相关方法创建的留言板
1 <html xmlns="http://www.w3.org/1999/xhtml"> 2 <head> 3 <style> 4 #ul1 {margin:0; padding:0;} 5 #ul1 li {list-style:none; width:300px; background:#CCC; border:1px solid #999; position:relative;} 6 #ul1 li h2 {display:inline-block;} 7 #ul1 li p {display:inline-block;} 8 #ul1 li a {position:absolute; right:4px; bottom:4px;} 9 </style> 10 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 11 <title>无标题文档</title> 12 <script type="text/javascript"> 13 window.onload=function (){ 14 var oName=document.getElementById('name'); 15 var oContent=document.getElementById('content'); 16 var oUl=document.getElementById('ul1'); 17 var oBtn=document.getElementById('btn1'); 18 var aLi=oUl.getElementsByTagName('li'); 19 var oLi=null; 20 21 oBtn.onclick=function (){ 22 oLi=document.createElement('li'); 23 var oH2=document.createElement('h2'); 24 var oP=document.createElement('p'); 25 var oA=document.createElement('a'); 26 27 oH2.innerHTML=oName.value+':'; 28 oP.innerHTML=oContent.value; 29 oA.innerHTML='删除'; 30 oA.href='javascript:;'; 31 oA.onclick=function (){ 32 oUl.removeChild(this.parentNode); 33 }; 34 35 oLi.appendChild(oH2); 36 oLi.appendChild(oP); 37 oLi.appendChild(oA); 38 39 if(aLi.length>0){ 40 oUl.insertBefore(oLi, aLi[0]); //确保新添加的在最前面 41 } 42 else{ 43 oUl.appendChild(oLi); 44 } 45 }; 46 }; 47 </script> 48 </head> 49 <body> 50 姓名:<input id="name" type="text" /><br /> 51 内容:<textarea id="content" rows="5" cols="40"></textarea><br /> 52 <input id="btn1" type="button" value="留言" /> 53 <ul id="ul1"> 54 </ul> 55 </body> 56 </html>