当前位置: 首页 > 网络学院 > XML相关教程 > XML DOM > replaceChild() 方法

XML DOM
DOM 节点
DOM 节点列表
DOM 解析
DOM 遍历节点树
DOM Mozilla 和 IE
DOM 获取节点
DOM 设置节点
DOM 删除节点
DOM 更换节点
DOM 建立节点
DOM 添加节点
DOM 克隆节点
DOM 节点类型
DOM Node
DOM NodeList
DOM NamedNodeMap
DOM Document
DOM DocumentType
DOM ProcessingInstr
DOM Element

XML DOM 中的 replaceChild() 方法


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-03-04   浏览: 383 ::
收藏到网摘: n/a

Definition and Usage
定义和用法

The replaceChild() method replaces a child node with another.
replaceChild()方法的作用是:用另一个节点替换一个子节点。

This function returns the replaced node on success, or NULL on failure.
如果函数执行成功,将返回替换的节点;如果执行失败,将返回null[空值]。

Syntax
语法

elementNode.removeChild(new_node,old_node)

Parameter
参数
Description
描述
new_node Required. Specifies the new node
必要参数。指定新的节点
old_node Required. Specifies the child node to replace
必要参数。指定需要替换的子节点
 

In all examples, we will use the XML file books.xml, and the JavaScript function loadXMLDoc().
在所有案例中,我们将使用“book.xml”文件以及JavaScript 函数“loadXMLDoc()”。

Example
案例

The following code fragment replaces the first <title> element in the first <book> elements of "books.xml":
下面的代码片断替换了“books.xml”文件中的第一个<book>元素中的第一个<title>元素:

//check if first child node is an element node
function get_firstchild(n) { var x=n.firstChild; while (x.nodeType!=1) { x=x.nextSibling; } return x; }
xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName("book")[0];
//create a title element and a text node
var newNode=xmlDoc.createElement("title");
var newText=xmlDoc.createTextNode("Giada's Family Dinners");
//add the text node to the title node,
newNode.appendChild(newText);
//replace the last node with the new node
x.replaceChild(newNode,get_firstchild(x));
var y=xmlDoc.getElementsByTagName("title");
for (i=0;i<y.length;i++) { document.write(y[i].childNodes[0].nodeValue); document.write("<br />"); }

Output:
输出结果:

Giada's Family Dinners
Harry Potter
XQuery Kick Start
Learning XML

Internet Explorer will skip white-space text nodes that are generated between nodes (e.g. new-line characters), while Mozilla will not. So, in the example above, we have created a function to get the right "firstChild" element.
IE将跳过在节点之间产生的空格文档节点(如:换行字符),而Mozilla不会这样。在下面的案例中,我们将创建一个用于获取正确“lastChild[第一个子元素]”的函数。

To read more about the differences between IE and Mozilla browers, visit our Mozilla vs. IE chapter in our XML DOM Tutorial.
如果你想获取更多关于IE和Mozilla浏览器的不同,那你可以访问XML DOM教程中的“Mozilla vs. IE ”这章。


Try-It-Yourself Demos
自我演示

replaceChild() - Replace an element node
replaceChild() - 替换一个元素节点

评论 (0) All

登陆 | 还没注册?