js:appendChild、insertBefore和insertAfter


web/Win8開發中經常要在js中動態增加一些element,就需要用到下面的一些方法:

appendChild:

target.appendChild(newChild)

newChild作為target的子節點插入最后的一子節點之后

insertBefore:

target.insertBefore(newChild,existingChild)

newChild作為target的子節點插入到existingChild節點之前

existingChild為可選項參數,當為null時其效果與appendChild一樣

 

insertAfter: 

顧名思義,就是在node后面增加new node,但是沒有現成的API提供調用,但也很容易的自己可以寫:

function insertAfter(newEl, targetEl)
{
    var parentEl = targetEl.parentNode;
            
     if(parentEl.lastChild == targetEl)
     {
           parentEl.appendChild(newEl);
      }else
      {
           parentEl.insertBefore(newEl,targetEl.nextSibling);
       }            
}

 


免責聲明!

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



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