看板 Mesak
作者 標題 [JS] JavaScript之appendChild、insertBefore和insertAfter
時間 2012年12月25日 Tue. PM 05:13:13
JavaScript之appendChild、insertBefore和insertAfter
appendChild定義
appendChild(newChild: Node) : Node
Appends a node to the childNodes array for the node.
Supported: IE 5.0+, Mozilla 1.0+, Netscape 6.0+, Safari 1.0+, Opera 7.0+
添加一個節點到指定的節點的子節點數組中,讀起來好像有點拗口,簡單地說就是將元素添加到指定的節點中
appendChild用法
target.appendChild(newChild)
newChild作為target的子節點插入最後的一子節點之後
appendChild例子newChild作為target的子節點插入最後的一子節點之後
var newElement = document.Document.createElement('label');
newElement.Element.setAttribute('value', 'Username:');
var usernameText = document.Document.getElementById('username');
usernameText.appendChild(newElement);
insertBefore定義newElement.Element.setAttribute('value', 'Username:');
var usernameText = document.Document.getElementById('username');
usernameText.appendChild(newElement);
The insertBefore() method inserts a new child node before an existing child node.
insertBefore() 方法的作用是:在現有的子節點前插入一個新的子節點
[b]insertBefore用法[/b]
[code=js]
target.insertBefore(newChild,existingChild)
newChild作為target的子節點插入到existingChild節點之前
existingChild為可選項參數,當為null時其效果與appendChild一樣
insertBefore例子insertBefore() 方法的作用是:在現有的子節點前插入一個新的子節點
[b]insertBefore用法[/b]
[code=js]
target.insertBefore(newChild,existingChild)
newChild作為target的子節點插入到existingChild節點之前
existingChild為可選項參數,當為null時其效果與appendChild一樣
var oTest = document.getElementById("test");
var newNode = document.createElement("p");
newNode.innerHTML = "This is a test";
oTest.insertBefore(newNode,oTest.childNodes[0]);
好了那麼有insertBefore的應該也有insertAfter吧?var newNode = document.createElement("p");
newNode.innerHTML = "This is a test";
oTest.insertBefore(newNode,oTest.childNodes[0]);
好那我們來用Aptana編寫一個例子吧,但Aptana的智能提示告訴我其實沒有insertAfter這個方法
那麼就自己定義一個羅:)
insertAfter定義
function insertAfter(newEl, targetEl)
{
var parentEl = targetEl.parentNode;
if(parentEl.lastChild == targetEl)
{
parentEl.appendChild(newEl);
}else
{
parentEl.insertBefore(newEl,targetEl.nextSibling);
}
}
{
var parentEl = targetEl.parentNode;
if(parentEl.lastChild == targetEl)
{
parentEl.appendChild(newEl);
}else
{
parentEl.insertBefore(newEl,targetEl.nextSibling);
}
}
insertAfter用法與例子
var txtName = document.getElementById("txtName");
var htmlSpan = document.createElement("span");
htmlSpan.innerHTML = "This is a test";
insertAfter(htmlSpan,txtName);
將htmlSpan 作為txtName 的兄弟節點插入到txtName 節點之後var htmlSpan = document.createElement("span");
htmlSpan.innerHTML = "This is a test";
insertAfter(htmlSpan,txtName);
1、appendChild和insertBefore是做對節點的方法來使用的,而insertAfter只是自定義的一個函數
2、insertBefore相對於appendChild來說,比較靈活可以將新的節點插入到目標節點子節點數組中的任一位置。
3、使用appendChild和insertBefore來插入新的節點前提是,其兄弟節點必須有共同的父節點
http://www.cnblogs.com/samlin/archiv...-insertBefore-insertAfter.html
--
Mesak Blog
http://mesak.oow.me
--
※ 作者: mesak 時間: 2012-12-25 17:13:13
※ 編輯: mesak 時間: 2012-12-25 17:14:40
※ 看板: Mesak 文章推薦值: 0 目前人氣: 0 累積人氣: 262
回列表(←)
分享