js使用dom操作實(shí)現(xiàn)簡(jiǎn)單留言板的方法

字號(hào):


    如圖所示簡(jiǎn)易留言板,也就是自?shī)首詷?lè)版,說(shuō)白了就是練習(xí)dom操作。
    js使用dom操作實(shí)現(xiàn)簡(jiǎn)單留言板的方法三聯(lián)
    要點(diǎn)一:document.createelement(標(biāo)簽名) 新建元素
    要點(diǎn)二:父元素.appendchild(元素) 把新建的元素插入到頁(yè)面的標(biāo)簽中(在標(biāo)簽的最后一個(gè)顯示),這樣才會(huì)在瀏覽器中顯示出來(lái)
    要點(diǎn)三:父元素.insertbefore(元素,要插入哪個(gè)元素的前面) 把新建的元素插入到頁(yè)面中指定的標(biāo)簽前面,這樣后面輸入的內(nèi)容才會(huì)顯示到前面
    要點(diǎn)四:父元素.removechild(元素) 刪除指定元素
    下面,上代碼:
    代碼如下:
    <!doctype html>
    <html>
    <head>
    <meta charset=utf-8 />
    <title>無(wú)標(biāo)題文檔</title>
    <script>
    window.onload = function(){
    var omsg = document.getelementbyid(msg);
    var obtn = document.getelementbyid(btn);
    var omsg_c = document.getelementbyid(msg_c);
    var oul = document.createelement(ul);
    omsg_c.appendchild(oul);
    obtn.onclick = function(){
    var sval = omsg.value;
    var oli = document.createelement(li);
    oli.innerhtml = sval + <span>刪除</span>;
    var oli1 = oul.getelementsbytagname(li);
    if(oli1.length>0){
    oul.insertbefore(oli,oli1[0]);
    }else{
    oul.appendchild(oli);
    }
    omsg.value='';
    var ospan = document.getelementsbytagname(span);
    for(var i=0; i<ospan.length; i++){
    ospan[i].onclick = function(){
    oul.removechild(this.parentnode);
    }
    }
    }
    }
    </script>
    </head>
    <body>
    <h1>簡(jiǎn)易留言板</h1>
    <input id=msg type=text size=40 value=>
    <input id=btn type=button value=留言>
    <div id=msg_c></div>
    </body>
    </html>