【问题标题】:Reversing order of items in DOMNodeList颠倒DOMNodeList中项目的顺序
【发布时间】:2011-04-19 18:24:13
【问题描述】:

你好 我正在制作 RSS 阅读器,并且正在使用 DOM。
现在我卡住了,试图颠倒 DOMNodeList 中项目的顺序。
我可以用 2 个周期完成它 - 一个将其作为数组,一个用于 rsort()
有什么办法可以颠倒DOMNodeList中的顺序还是必须用“数组方式”来完成?

【问题讨论】:

    标签: php dom reverse


    【解决方案1】:

    为什么不在客户端使用 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)
    }
    

    【讨论】:

    • 这是一个 PHP 问题,不是 Javascript 问题。
    【解决方案2】:

    没有反转 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)

    【讨论】:

    • 如何从终点走到起点?
    【解决方案3】:

    使用 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);
    }
    

    【讨论】:

    • 方法cloneNode在DOMNodeList的当前实现中似乎不存在。
    猜你喜欢
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 2016-11-20
    • 1970-01-01
    • 2022-12-28
    相关资源
    最近更新 更多