當(dāng)前位置:軟件學(xué)堂 > 資訊首頁 > 網(wǎng)絡(luò)編程 > 編程其他 > 使用DoM實(shí)現(xiàn)控件的替換

使用DoM實(shí)現(xiàn)控件的替換

2012/11/11 15:55:36作者:佚名來源:網(wǎng)絡(luò)

移動端

【實(shí)例名稱】

使用DoM實(shí)現(xiàn)控件的替換

【實(shí)例描述】

本鍘實(shí)現(xiàn)兩個(gè)div內(nèi)元素互換,主要依靠DOM的“replaceChild”方法。

【實(shí)例代碼】

<html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>標(biāo)題頁-學(xué)無憂(www.wangbatian.cn)</title> <script type="text/javascript"> function test()     {         var mydom1=document.getElementById("divlist1"); //獲取指定ID的DOM對象         var mydom2=document.getElementById("divlist2"); //獲取指定ID的DOM對象         mydom1.replaceChild(mydom2.firstChild,mydom1.firstChild);     } </script>

</head> <body> <form id="form1" runat="server">       <input id="btn1" type="button" value="test" onclick="test()"/>       <div id="divlist1"><p>this is test1</p></div>       <div id="divlist2"><p>this is test2</p></div>     </form>

</body> </html>

 

【運(yùn)行效果】

                                          初始運(yùn)行效果

使用DoM實(shí)現(xiàn)控件的替換運(yùn)行效果

                                         替換后的效果

使用DoM實(shí)現(xiàn)控件的替換運(yùn)行效果

【難點(diǎn)剖析】

替換節(jié)點(diǎn)需要使用DOM中的“replaceChild”方法。需要注意的是此代碼的運(yùn)行結(jié)果是“mydoml”中的元素被替換了,而“mydom2”的元素就沒有了,“replaceChild”方法相當(dāng)于轉(zhuǎn)移。

【源碼下載】

為了JS代碼的準(zhǔn)確性,請點(diǎn)擊:使用DoM實(shí)現(xiàn)控件的替換 進(jìn)行本實(shí)例源碼下載 

標(biāo)簽: DoM實(shí)現(xiàn)  控件  替換