首頁  >  文章  >  web前端  >  基於JavaScript建立動態Dom_javascript技巧

基於JavaScript建立動態Dom_javascript技巧

WBOY
WBOY原創
2016-05-16 15:26:581042瀏覽

動態腳本

我們在頁面中使用<script>元素就可以在頁面中插入javascript程式碼。有兩種方式:一種是透過src屬性來引用外部的JS文件,一種是用這個元素來包含一段js程式碼。所謂的動態腳本,就是指這個腳本在頁面載入時不存在,在未來的某個時刻透過修改DOM來動態的新增腳本。與操作html元素一樣,建立動態腳本也有兩種方式:插入外部檔案和直接插入JavaScript程式碼。 </script>

動態載入的外部JavaScript程式碼可以立刻執行,例如下面的程式碼:

var script = document.createElement("script");
script.type = "text/javascript";
script.src = "demo.js";
document.body.appendChild(script);

從上圖的結果可以看到,上面程式碼在

元素中產生了一個<script>節點: <div class="jb51code"> <pre class="brush:js;"> &lt;script type=&quot;text/javascript&quot; src=&quot;demo.js&quot;&gt;&lt;/script&gt; </pre> <p>要注意的是,在執行最後一行程式碼把<script>加入到頁面之前,是不會下載外部腳本檔的。 <p>另一種指定JavaScript程式碼的方式是行內方式,例如: <div class="jb51code"> <pre class="brush:js;"> var script = document.createElement(&quot;script&quot;); script.type = &quot;text/javascript&quot;; script.appendChild(document.createTextNode(&quot;function fn1(){alert('hello wolrd!')} fn1();&quot;)); document.body.appendChild(script); </pre> <p style="text-align: center"><img id="theimg" alt="" baiduimageplusrect="null" baiduimageplusstatus="2" onclick="window.open(this.src)" src="http://files.jb51.net/file_images/article/201512/2015128143006554.jpg&#63;2015118143027" /> <p>上面的程式碼會在<body>元素中插入一段JavaScript程式碼: <div class="jb51code"> <pre class="brush:js;"> &lt;script type=&quot;text/javascript&quot;&gt; function fn1(){alert('hello wolrd!')} fn1(); &lt;/script&gt; </pre> <p>執行上面的程式碼後會彈出提示框,顯示「hello world!」文字。 <p>在Firefox、Safari、Chrome和Opera瀏覽器中,上面操作的DOM程式碼是可以正常執行的。但是在舊版的IE瀏覽器中,這些程式碼會發生錯誤。舊版的IE瀏覽器將<script>元素看做特殊元素,不允許DOM存取它的子節點。不過,可以使用<script>元素的text屬性來指定JavaScript程式碼,例如: <div class="jb51code"> <pre class="brush:js;"> var script = document.createElement(&quot;script&quot;); script.type = &quot;text/javascript&quot;; script.text(&quot;function fn1(){alert('hello wolrd!')} fn1();&quot;); document.body.appendChild(script); </pre> <p>像上面這樣修改程式碼之後,都可以在IE、Firefox、Safari3.0、Chrome和Opera瀏覽器中運作。 Safari3.0之前的瀏覽器雖然無法正確的執行text屬性,但可以使用文字節點來指定程式碼。所以如果需要支援舊版的瀏覽器,可以像下面這樣書寫程式碼: <div class="jb51code"> <pre class="brush:js;"> var script = document.createElement(&quot;script&quot;); script.type = &quot;text/javascript&quot;; var code = &quot;function fn1(){alert('hello wolrd!')} fn1();&quot;; try{ script.appendChild(document.createTextNode(code)); }catch(e){ script.text = code; }</pre> <p>上面的程式碼首先嘗試標準的DOM文字節點方法,因為除了舊版的IE瀏覽器之外,其它瀏覽器都支援這種方式。如果這行程式碼拋出異常,那麼表示是舊版的IE瀏覽器,那就必須使用text屬性。 <p>我們可以將動態新增腳本的程式碼封裝到一個函數中,透過不同的參數來動態載入不同的腳本。 <div class="jb51code"> <pre class="brush:js;"> function loadScript(code){ var script = document.createElement(&quot;script&quot;); script.type = &quot;text/javascript&quot;; try{ script.appendChild(document.createTextNode(code)); }catch(e){ script.text = code; } document.body.appendChild(script); } </pre> <p>要呼叫這個函數,可以像下面的樣子: <div class="jb51code"> <pre class="brush:js;"> loadScript(&quot;function fn1(){alert('hello wolrd!')}&quot;); </pre> <p>這種方式載入的程式碼會在全域作用域中執行,而且當腳本執行後立刻可用。實際上,這樣執行程式碼與在全域作用域中把相同的字串傳遞給eval()函數是一樣的。 <p><strong><span style="color: #0000ff">動態樣式 <p>通常可以將CSS樣式包含到HTML頁面中的元素有兩個:一個是<link>元素,用於包含來自外部的檔案;另一個是<style>元素,用於指定嵌入樣式。與動態腳本類似,動態樣式是指在頁面載入時並不存在的樣式。動態樣式是在頁面載入完成後動態新增到頁面中的腳本。例如下面的範例: <div class="jb51code"> <pre class="brush:js;"> var link = document.createElement(&quot;link&quot;); link.rel = &quot;stylesheet&quot; link.type = &quot;text/css&quot;; link.href = &quot;styles.css&quot;; var head = document.getElementsByTagName(&quot;head&quot;)[0];</pre> <p style="text-align: center"><img id="theimg" alt="" baiduimageplusrect="null" baiduimageplusstatus="2" onclick="window.open(this.src)" src="http://files.jb51.net/file_images/article/201512/2015128143341450.jpg&#63;2015118143357" /> <p>以上的程式碼在所有主流的瀏覽器中都可以正常運作。需要注意的是<link>元素要加入<head>元素中,而不是<body>元素中,才能確保所有瀏覽器中的行為一致。 <p>另外要注意的是,載入外部樣式檔案的過程是異步的,也就是說載入樣式和執行JavaScript程式碼的過程沒有固定的次序。 <p>另一個定義樣式的方式是使用<style>元素來包含嵌入式的CSS樣式。例如下面的程式碼: <div class="jb51code"> <pre class="brush:js;"> var style = document.createElement(&quot;style&quot;); style.type = &quot;text/css&quot;; style.appendChild(document.createTextNode(&quot;body{background:#f00;}&quot;)); var head = document.getElementsByTagName(&quot;head&quot;)[0]; head.appendChild(link); </pre> <p>上面的程式碼執行後可以在<head>元素中動態加入下面的節點: <div class="jb51code"> <pre class="brush:js;"> &lt;style type=&quot;text/css&quot;&gt; background:#f00; &lt;/style&gt; </pre> <p>以上的代码可以在Firefox、Safari、Chrome和Opera浏览器中正常运行,在旧版本的IE浏览器中会报错。旧版本的IE浏览器会将c9ccee2e6ea535a969eb3f532ad9fe89元素看做一个特殊的节点,不允许访问它的子节点。要解决旧版本IE的问题,就是访问元素的styleSheet属性,该属性又有一个cssText属性,可以接受CSS代码。例如下面的代码: <div class="jb51code"> <pre class="brush:js;"> var style = document.createElement(&quot;style&quot;); style.type = &quot;text/css&quot;; try{ style.appendChild(document.createTextNode(&quot;body{background:#f00;}&quot;)); }catch(e){ style.styleSheet.cssText = &quot;body{background:#f00;}&quot;; } </pre> <p>同样,我们也可以将动态添加样式的代码封装到一个函数中,通过不同的参数来动态加载不同的样式。 <div class="jb51code"> <pre class="brush:js;"> function loadStyle(code){ var style = document.createElement(&quot;style&quot;); style.type = &quot;text/css&quot;; try{ style.appendChild(document.createTextNode(code)); }catch(e){ style.styleSheet.cssText = code; } var head = document.getElementsByTagName(&quot;head&quot;)[0]; head.appendChild(style); } </pre> <p><strong><span style="color: #0000ff">JavaScript对表格的操作 <p>在JavaScript中,为了使我们能够方便的构建表格,HTML DOM为表格的f5d188ed2c074f8b944552db028f98a1、92cee25da80fac49f6fb6eec5fd2c22a和a34de1251f0d9fe1e645927f19a896e8提供了一些属性和方法。 <p>表格的f5d188ed2c074f8b944552db028f98a1元素的属性和方法有: <p>caption:保存63bd76834ec05ac1f4c0ebbeaafb0994元素的引用的指针。<br /> tBodies:是一个92cee25da80fac49f6fb6eec5fd2c22a元素的HTMLCollection。<br /> tFoot:保存06669983c3badb677f993a8c29d18845元素的引用的指针。<br /> tHead:保存ae20bdd317918ca68efdc799512a9b39元素的引用的指针。<br /> rows:是表格中所有行的HTMLCollection。<br /> createTHead():创建ae20bdd317918ca68efdc799512a9b39元素,将它放入表格中,并返回其引用。<br /> createTFoot():创建06669983c3badb677f993a8c29d18845元素,将它放入表格中,并返回其引用。<br /> createCaption():创建63bd76834ec05ac1f4c0ebbeaafb0994元素,将它放入表格中,并返回其引用。<br /> deleteTHead():删除ae20bdd317918ca68efdc799512a9b39元素。<br /> deleteTFoot():删除06669983c3badb677f993a8c29d18845元素<br /> deleteCaption():删除63bd76834ec05ac1f4c0ebbeaafb0994元素<br /> deleteRow(pos):删除指定位置的表格行。<br /> insertRow(pos):向rows集合中指定位置插入一行。 <p><span style="color: #ff0000"><strong>表格的92cee25da80fac49f6fb6eec5fd2c22a元素的属性和方法有: <p><br /> <p>rows:保存着92cee25da80fac49f6fb6eec5fd2c22a元素中行的HTMLCollection。<br /> deleteRow(pos):删除指定位置的表格行。<br /> insertRow(pos):向rows集合中指定位置插入一行。 <p><strong><span style="color: #ff0000">表格的a34de1251f0d9fe1e645927f19a896e8元素的属性和方法有: <p>cells:保存着a34de1251f0d9fe1e645927f19a896e8元素中单元格的HTMLCollection。<br /> deleteCell(pos):删除指定位置的单元格。<br /> insertCell(pos):向cells集合中指定位置插入一个单元格,并返回新插入单元格的引用。 <p>使用上面的这些属性和方法,可以使我们轻松的使用JavaScript来创建表格,例如下面的代码: <div class="jb51code"> <pre class="brush:js;"> //创建表格 vatabldocument.createElement(&quot;table&quot;); table.borde1; table.widt&quot;100%&quot;; //创建tbody vatboddocument.createElement(&quot;tbody&quot;); table.appendChild(tbody); //创建第一个表格行 tbody.insertRow(0); tbody.rows[0].insertCell(0); tbody.rows[0].cells[0].appendChild(document.createTextNode(&quot;单元1-1&quot;)); tbody.rows[0].insertCell(1); tbody.rows[0].cells[1].appendChild(document.createTextNode(&quot;单元2-1&quot;)); //创建第二个表格行 tbody.insertRow(1); tbody.rows[1].insertCell(0); tbody.rows[1].cells[0].appendChild(document.createTextNode(&quot;单元1-2&quot;)); tbody.rows[1].insertCell(1); tbody.rows[1].cells[1].appendChild(document.createTextNode(&quot;单元2-2&quot;)); //将表格添加到文档中 document.body.appendChild(table) </pre> <p>使用上面的代码可以动态的在页面中创建一个表格。其中在创建表格行的时候,通过92cee25da80fac49f6fb6eec5fd2c22a元素调用了insertCell()方法,并传入参数0(表示将插入的行放在什么位置上)。执行了这一行代码后,会自动创建一个表格行,并将它插入到92cee25da80fac49f6fb6eec5fd2c22a元素的0位置上,此时就可以通过tbody.rows[0]来引用新插入的行。 <p>创建单元格的方式也与创建表格行的方式相同。通过a34de1251f0d9fe1e645927f19a896e8元素来调用insertCell()方法,并传入要放置单元格的位置。然后就可以通过tbody.rows[0].cells[0]来引用新插入的单元格。 <p>关于NodeList <p>理解NodeList和NamedNodeMap、HTMLCollection是从整体上理解DOM的关键所在。这3个集合都是动态的,也就是说,每当文档结构发生了变化,它们始终都会保存最新的信息。从本质上来说,所有的NodeList对象都是在访问DOM文档时实时运行的查询。例如下面的代码会导致死循环的出现: <div class="jb51code"> <pre class="brush:js;"> var divs = document.getElementsByTagName(&quot;div&quot;); for(var i = 0; i &lt; divs.length; i++){ var div = document.createElement(&quot;div&quot;); document.body.appendChild(div); } </pre> <p>上面的代码首先获取了所有dc6dce4a544fdca2df29d5ac0ea9906b元素的HTMLCollection,保存在一个变量中。由于这个集合是动态的,所以只要有新的dc6dce4a544fdca2df29d5ac0ea9906b被添加到页面中,新的dc6dce4a544fdca2df29d5ac0ea9906b元素就会被添加到这个集合中。这样导致的后果是div.length值是不断变化的,每次循环会在页面中添加一个dc6dce4a544fdca2df29d5ac0ea9906b元素,length的值也会递增。这样i < divs.length条件就永远不会成立,导致死循环的发生。 <p>如果我们要迭代一个NodeList,最好将length属性初始化为第二个变量,然后将迭代器和这个变量做比较,例如: <div class="jb51code"> <pre class="brush:js;"> var divs = document.getElementsByTagName(&quot;div&quot;); for(var i = 0,len = divs.length; i &lt; len; i++){ var div = document.createElement(&quot;div&quot;); document.body.appendChild(div); } </pre> <p>由于len中保存了divs.length在循环开始时的一个快照,因此会避免死循环情况的发生。 <p>更多示例: <div class="jb51code"> <pre class="brush:js;"> function sAlert(str){ var msgw,msgh,bordercolor; msgw=400;//提示窗口的宽度 msgh=100;//提示窗口的高度 titleheight=25 //提示窗口标题高度 bordercolor=&quot;#c51100&quot;;//提示窗口的边框颜色 titlecolor=&quot;#c51100&quot;;//提示窗口的标题颜色 var sWidth,sHeight; sWidth=screen.width; sHeight=screen.height; var bgObj=document.createElement(&quot;div&quot;); bgObj.setAttribute('id','bgDiv'); bgObj.style.position=&quot;absolute&quot;; bgObj.style.top=&quot;0&quot;; bgObj.style.background=&quot;#cccccc&quot;; bgObj.style.filter=&quot;progid:DXImageTransform.Microsoft.Alpha(style=3,opacity=25,finishOpacity=75&quot;; bgObj.style.opacity=&quot;0.6&quot;; bgObj.style.left=&quot;0&quot;; bgObj.style.width=sWidth + &quot;px&quot;; bgObj.style.height=sHeight + &quot;px&quot;; bgObj.style.zIndex = &quot;10000&quot;; document.body.appendChild(bgObj); var msgObj=document.createElement(&quot;div&quot;) msgObj.setAttribute(&quot;id&quot;,&quot;msgDiv&quot;); msgObj.setAttribute(&quot;align&quot;,&quot;center&quot;); msgObj.style.background=&quot;white&quot;; msgObj.style.border=&quot;1px solid &quot; + bordercolor; msgObj.style.position = &quot;absolute&quot;; msgObj.style.left = &quot;50%&quot;; msgObj.style.top = &quot;50%&quot;; msgObj.style.font=&quot;12px/1.6em Verdana, Geneva, Arial, Helvetica, sans-serif&quot;; msgObj.style.marginLeft = &quot;-225px&quot; ; msgObj.style.marginTop = -75+document.documentElement.scrollTop+&quot;px&quot;; msgObj.style.width = msgw + &quot;px&quot;; msgObj.style.height =msgh + &quot;px&quot;; msgObj.style.textAlign = &quot;center&quot;; msgObj.style.lineHeight =&quot;25px&quot;; msgObj.style.zIndex = &quot;10001&quot;; msgObj.style.position = &quot;absolute&quot;; var box=document.getElementById(str); var title=document.createElement(&quot;h4&quot;); title.setAttribute(&quot;id&quot;,&quot;msgTitle&quot;); title.setAttribute(&quot;align&quot;,&quot;right&quot;); title.style.margin=&quot;0&quot;; title.style.padding=&quot;3px&quot;; title.style.background=bordercolor; title.style.filter=&quot;progid:DXImageTransform.Microsoft.Alpha(startX=20, startY=20, finishX=100, finishY=100,style=1,opacity=75,finishOpacity=100);&quot;; title.style.opacity=&quot;0.75&quot;; title.style.border=&quot;1px solid &quot; + bordercolor; title.style.height=&quot;18px&quot;; title.style.font=&quot;12px Verdana, Geneva, Arial, Helvetica, sans-serif&quot;; title.style.color=&quot;white&quot;; title.style.cursor=&quot;pointer&quot;; title.onmousedown=function(){startDrag(this,'msgDiv')}; title.onmouseup=function(){stopDrag(this,'msgDiv')}; title.onmousemove=function(){drag('msgDiv')}; var closer=document.createElement(&quot;div&quot;); closer.onclick=function(){ CloseReturn(); document.body.appendChild(box); box.style.display = &quot;none&quot;; document.body.removeChild(bgObj); document.getElementById(&quot;msgDiv&quot;).removeChild(title); document.body.removeChild(msgObj); }; closer.innerHTML=&quot;确定&quot;; document.body.appendChild(msgObj); document.getElementById(&quot;msgDiv&quot;).appendChild(title); document.getElementById(&quot;msgTitle&quot;).appendChild(closer); box.style.display=&quot;inline&quot;; document.getElementById(&quot;msgDiv&quot;).appendChild(box); ShowReturn(); }</pre> <p>html dom樹: <p style="text-align: center"><img id="theimg" onclick="window.open(this.src)" src="http://files.jb51.net/file_images/article/201512/2015128143651942.gif&#63;201511814375" baiduimageplusstatus="2" baiduimageplusrect="null" alt="" /></script>
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn