【发布时间】:2011-04-19 18:24:13
【问题描述】:
你好
我正在制作 RSS 阅读器,并且正在使用 DOM。
现在我卡住了,试图颠倒 DOMNodeList 中项目的顺序。
我可以用 2 个周期完成它 - 一个将其作为数组,一个用于 rsort()。
有什么办法可以颠倒DOMNodeList中的顺序还是必须用“数组方式”来完成?
【问题讨论】:
你好
我正在制作 RSS 阅读器,并且正在使用 DOM。
现在我卡住了,试图颠倒 DOMNodeList 中项目的顺序。
我可以用 2 个周期完成它 - 一个将其作为数组,一个用于 rsort()。
有什么办法可以颠倒DOMNodeList中的顺序还是必须用“数组方式”来完成?
【问题讨论】:
为什么不在客户端使用 javascript 来做呢? 给定节点 n 的代码是:
function reverse(n) { // Reverses the order of the children of Node n
var f = document.createDocumentFragment( ); // Get an empty DocumentFragment
while(n.lastChild) // Loop backward through the children,
f.appendChild(n.lastChild); // moving each one to the DocumentFragment
n.appendChild(f); // Then move them back (in their new order)
}
【讨论】:
没有反转 DOMNodeList 的方法。
但是你可以保持原样,如果你需要它,从头到尾遍历它。
例子:
<?php
$doc=new DOMDocument;
$doc->loadXML('
<div>
<span>1
<span>2
<span>3
</span>
</span>
</span>
</div>');
$nodeList=$doc->getElementsByTagName('span');
for($n=$nodeList->length-1;$n>=0;--$n)
{
echo $nodeList->item($n)->firstChild->data;//returns 321
}
?>
只需使用NodeList->length指向NodeList的末尾,然后递减索引并访问NodeList->item(index)
【讨论】:
使用 documentFragment 的替代方法(可能以不需要的“默认:”命名空间前缀结束):克隆 NodeList,将所有项目转移到克隆,然后替换原始节点:
function reverseNodeList($nodeList) {
// clone the original node
$reverseNodeList = $nodeList->cloneNode();
// move all nodes off the bottom of the original list onto the new one
while ($nodeList->lastChild) $reverseNodeList->appendChild($nodeList->lastChild);
// replace the original node with the new one
$nodeList->parentNode->replaceChild($reverseNodeList, $nodeList);
}
【讨论】: