JavaScript(appendChild添加節點)


首先,我們有一個編輯器,有一個簡單的HTML頁面,頁面的級別分別 --> html  -->head[title,meta,script,link] -- body,然后再新建一個index.js頁面,專門編寫javascript代碼。后面再建一個style.css頁面。

html頁面

 

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
    <title>DOM</title>
    <link rel="stylesheet" type="text/css" href="css/style.css" />
    <script src="js/Demo.js"></script>
</head>
<body>
    <div class="main" id="main">
        <center>
            <div id="test"></div>
        </center>
    </div>
</body>
</html>
View Code

 

css頁面

html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio,video
{margin: 0; padding: 0; border: 0; font-size: 100%; font: "Microsoft Himalaya"; vertical-align:baseline;}
body
{font-size: 1.025rem;}
/*固定css樣式--頂部代碼*/
.main
{position:absolute;top:0;bottom:0;left:0;right:0;background-color:#b9b7b7;}
.main center
{position:absolute;top:2%;bottom:2%;left:1%;right:1%;background-color:#ffffff;border-radius:12px;}
.main center div#test
{position:relative;margin:1% auto;padding:6px 0px;background:rgba(242, 248, 248, 0.93);border:1px solid rgba(241, 242, 243, 0.95);box-shadow:2px 0px 2px #ffffff;}
css

 

javascript頁面

function div(){
    var test = document.getElementById("test");
    
    var p = document.createElement("p");
    var i = document.createElement("i");
    var text = "this is javaScript";
    var here = document.createTextNode(text);
        i.appendChild(here);
        p.appendChild(i);//在p內增加一個i文本

        test.appendChild(p);//在div內增加一個p節點
}
View Code

 

此時,在web瀏覽器看到頁面上顯示的信息,this isjavascript英文字斜的表示用了<i>標簽。

在html頁面,我們只是在body內給div塊新建了一個id,然后,在javascript內通過getElementById(id)獲取頁面的id即可,后面通過appendchild來給節點添加子節點,就這樣一步一步走,不出意外,就可以實現我們想要的。

還沒有完,之前我們沒有說如何在頁面上加載js函數,所以在javascript頁面的function div(){}后面還要再加一行代碼。 window.onload=div;

寫到這里,也就搞定了,當然這些都是基礎,如果內容有問題,希望您提出來,以免誤導其他人學習,我希望大家互相成長。^_^

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM