【问题标题】:Traversing an html nested list using javascript使用javascript遍历html嵌套列表
【发布时间】:2011-08-13 18:22:00
【问题描述】:

我有一个页面的 HTML 列表(<ul><li> 等),其中包含不同深度的多个项目。我正在尝试编写一些代码来一次遍历这个列表一个元素。因此,“下一个”按钮将返回以下 <li> 元素的 ID,它可能是当前元素的直接兄弟元素,也可能位于子 <ul> 元素中,也可能位于父元素 @987654325 中@ 元素。同样,“prev”按钮也可以做同样的事情,但相反。

这里是一些示例 html:

<ul>
  <li id="post_item_1"><a href="#post1">Vestibulum ultrices, ante non tincidunt molestie, purus enim varius urna, nec bibendum...</a>

   <ul>
   <li id="post_item_26"><a href="#post26">This planet has &mdash; or rather had &mdash; a problem, which was this: most of...</a>

    <ul>
    <li id="post_item_27"><a href="#post27">A towel, it says, is about the most massively useful thing an interstellar hitch...</a>
    </li>
   </ul>

   </li>
  </ul>
  </li>
  <li id="post_item_2"><a href="#post2">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nec velit augue,...</a>

   <ul>
   <li id="post_item_58"><a href="#post58">Reply to first post, with an edit</a>
   </li>

   <li id="post_item_59"><a href="#post59">Another reply to first post, made after the first reply</a>
   </li>
  </ul>
  </li>
  <li id="post_item_4"><a href="#post4">Phasellus vitae est tellus, vel aliquam lectus. Cras augue tellus, pulvinar a blandit...</a>

   <ul>
   <li id="post_item_60"><a href="#post60">Reply to second post</a>

   </li>
  </ul>
  </li>
  <li id="post_item_3"><a href="#post3">Pellentesque consequat urna mauris, luctus adipiscing enim. Sed quis lectus vel...</a>
  </li>
  <li id="post_item_28"><a href="#post28">"The Babel fish" said The Hitchhiker's Guide to the Galaxy quietly, "is small, yellow...</a>

  </li>
  <li id="post_item_61"><a href="#post61">Hello there, it is very worrying</a>

   <ul>
   <li id="post_item_62"><a href="#post62">Don't be scared, or scarred, or sacred, or Skesis!</a>
   </li>
  </ul>
  </li>

  <li id="post_item_67"><a href="#post67">Well, to be fair, at the end of the day, when all is said and done, I'd like to...</a>
  </li>
</ul>

我已经用 jquery 玩了几个小时了,这就是我所掌握的:

if (!node) {
// start with the selected node
node = $('#content #postNavigator ul li.selected')
}   


if ( $(node).has('ul').length ) {
    // has child <ul> 
nextNode = $($(node).children()[1]).children()[0];      
} 
else {
// has a sibling
if ($(node).next('li').length) {
    nextNode = $(node).next('li');
}
else {  

    // recursion needed here - this code will return parent, but only when 1 level deep.
    if ($(node).parent().parent().next('li').length) {
        nextNode = $(node).parent().parent().next('li');
    }
    else {          
        return false;
        }
    }               
}

上面将返回下一个节点,如果有则返回子节点,如果没有更多兄弟节点或子节点,则返回父节点,但只有一层深。 HTML 列表可以是无限深度的,所以可能需要某种递归?这是我的技能所能带给我的。我什至还没有开始考虑“上一个”链接,以相同的方式但以相反的顺序处理此列表。

我(几周前)在 devshed 上问过同样的问题,但没有得到任何答复。


谢谢大家的回答。

忍者,我已经成功地实现了你的。我现在可以很好地上下导航我的嵌套列表。

如果您愿意,还有一个问题:我需要能够在树中的某个点开始“位置”。用户可以通过哈希(例如#post9)在树中选择一个节点 - 他们可以单击列表中任意位置的节点来选择它,或者他们可以将包含该节点自己的哈希的 url 加入书签。

所以我的进一步问题是:我将如何使用 URL 中的哈希定位树中的节点并获取它的位置? URL 中的哈希与 li 节点的 id 相关 .

【问题讨论】:

    标签: javascript dom tree-traversal


    【解决方案1】:

    既然您已经在使用 jQuery,那么您不妨利用其内置的 DOM 遍历机制。在这种情况下,您将主要关心$().find$().eq

    $().find

    jQuery 实际上可以找到存在于任何其他选择器级别之下的每个匹配元素。这种单一方法将为您完成大部分工作。

    // Returns a jQuery object containing every 'li' on the page
    var items = $('body').find('li');
    

    $().eq

    真的,您现在有几个选项可以访问这些单独的li 元素。 jQuery 是一个类似数组的结构,这意味着您可以通过索引访问每个元素。 但是 jQuery 也有一个内置方法可以从集合中取出单个元素,它们也会作为 jQuery 对象返回。

    // Good: Returns the first element from the jQuery collection as a JS DOMElement
    items[0];
    
    // Better: Returns the first element from the jQuery collection as a jQuery collection
    items.eq(0);
    

    把它放在一起

    现在您已经掌握了工具,您只需应用一些逻辑即可从列表中的一个元素移动到下一个元素。这就是您真正需要的一切;我还将您的标记复制到了一个 jsFiddle 项目中,并添加了一些功能来向您展示它是如何工作的:http://jsfiddle.net/ninjascript/Kt8f8/

    var items = $('body').find('li');
    var length = items.length;
    var position = -1;
    
    function next() {
        position = (position + 1 < length) ? position + 1 : 0;
        return items.eq(position);
    }
    

    祝你好运!

    【讨论】:

    • 太好了,谢谢,也感谢其他人的回复。我已经发布了另一个问题的答案 - 我希望这是在 SO 上这样做的正确方法 - 我第一次发布!
    【解决方案2】:

    我相信这会奏效:

        function nextNode(selectedNode) {
        var nextNode = selectedNode.next("li");
        if (nextNode.length) {
            return nextNode;
        }
    
        return nextNode.closest("li").next();
    }
    

    它的作用是获取选定的节点并返回下一个节点(如果有的话)。如果没有,它会搜索最近的父 li 标签并从他那里获取下一个节点。

    【讨论】:

      【解决方案3】:

      如果你不想使用外部库,那么你需要结合使用 javascript document methods

      dom element methods

      祝你好运!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-22
        • 2015-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-06
        • 2021-09-19
        相关资源
        最近更新 更多