【发布时间】: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 — or rather had — 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