Javascript中insertBefore的語句

來源:互聯網
上載者:User

     說起來汗顏,用了很久JS,基礎的DOM方法都不熟悉,哎,不說了,努力學習吧。

     今天晚上做了個關於insertBefore方法DEMO,功能很簡單,頁面上有幾個P標籤,一個下拉式清單顯示P的個數,然後一個按鈕負責在制定P標籤前插入一段文字。

     DEMO編程思路是這樣的,一共3個function:init()負責初始化和事件綁定,getPnum()負責動態獲得P標籤的個數並填充到下拉式清單中,addP()是主要功能實現。     My Code如下:

Code
<script type="text/javascript">
window.onload=init;
function init(){
    getPnum();
    document.getElementById("addP").onclick=function(){ addP()};
}

function getPnum(){
    var Pnum=document.getElementsByTagName("p").length;
    for(i=0;i<Pnum;i++)
    {
        document.getElementById("PNum").options[i]=new Option(i+1,i+1);
    }
}

function addP(){
    var thePindex=document.getElementById("PNum").selectedIndex;
    var allP=document.getElementsByTagName("p");
    var insertOB=allP.item(thePindex);
    var newP=document.createElement("p");
    var newText=document.createTextNode("這是在:" + new Date()+"插入的文本元素!");
    newP.appendChild(newText);
    document.getElementById("modifiable").insertBefore(newP,insertOB);
}

</script>

      經過幾次調試,終於實現了功能,也對insertBefor有了深入的瞭解。

insertBefor的用法:

      oElement = object . insertBefore ( oNewNode , oChildNode )

      在指定元素前插入元素或者文本,這需要在調用insertBefore的時候傳2個參數,第一個參數oNewNode 是要插入的元素,第二個參數oChildNode 是座標元素,比如有ABCD四個元素,需要將一段文本插入到B的前面,那麼參數二就是B。需注意的是這個時候oElement 必須是座標函數的父級元素

     oChildNode 是個選擇性參數,如果不填的話,為了保證該JS在Firefox下的相容性,應該傳個null進去。

     關於insertBefor語句就寫這麼多了:)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.