createElement 创建DOM元素

 1 <html xmlns="http://www.w3.org/1999/xhtml">
 2 <head>
 3 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 4 <title>无标题文档</title>
 5 <script type="text/javascript">
 6 window.onload=function (){
 7     var $ = function(id){
 8         return document.getElementById(id);
 9     }
10     
11     var oBtn=$('btn1');
12     var oTxt=$('txt1');
13     var oUl=$('ul1');
14     var aLi=oUl.getElementsByTagName('li');
15     
16     oBtn.onclick=function (){
17         //用DOM方法创建出来的元素,和普通元素没有任何区别
18         var oLi=document.createElement('li');
19         
20         oLi.innerHTML=oTxt.value;
21         
22         //oUl.appendChild(oLi); 用此句会添加到最后,下面会添加到最前面
23         if(aLi.length>0){
24             oUl.insertBefore(oLi, aLi[0]); // insertBefore(节点,在谁之前插入)
25         }
26         else{
27             oUl.appendChild(oLi); // 用法: appendChild(节点);
28         }
29     };
30 };
31 </script>
32 </head>
33 <body>
34 <input id="txt1" type="text" />
35 <input id="btn1" type="button" value="创建Li" />
36 <ul id="ul1">
37 
38 </ul>
39 </body>
40 </html>

 Document类型定义了创建Element和Text对象的方法,Node类型定义了在节点树中插入、删除和替换的方法。

1 // 从指定的URL,异步加载和执行脚本
2 function loadasync(url){
3     var head = document.getElementsByTagName('head')[0];  //查找文档的<head>标签
4     var s = document.createElement('script'); //创建一个<script>元素
5     s.src = url; //设置它的src属性值
6     head.appendChild(s);
7 }

 

posted @ 2013-08-06 15:42  远方的远方  阅读(660)  评论(0编辑  收藏  举报