反转DOMNodeList中项目的顺序

时间:2010-10-01 09:16:36

标签: php dom reverse

您好 我正在制作RSS阅读器而我正在使用DOM 现在我卡住了,试图改变DOMNodeList中项目的顺序 我可以使用2个循环 - 一个用于制作数组,一个用于 rsort()
有没有办法扭转DOMNodeList中的顺序,或者必须使用“数组方式”?

3 个答案:

答案 0 :(得分:5)

没有用于反转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-&gt; length 指向NodeList的末尾,然后递减索引并访问 NodeList-&gt; item(index)

答案 1 :(得分:0)

使用documentFragment的替代方法(最终可以使用不需要的“default:”命名空间前缀):克隆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);
}

答案 2 :(得分:-2)

为什么不使用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)
}
相关问题