ページの HTML リスト ( <ul>
、<li>
など) があり、複数のアイテムがさまざまな深さにあります。このリストを一度に 1 要素ずつトラバースするコードを作成しようとしています。そのため、「次へ」ボタンは次の<li>
要素の ID を返します。これは、現在の要素の直接の兄弟であるか、子<ul>
要素にあるか、親<ul>
要素にある可能性があります。同様に、「前へ」ボタンも同じことを行いますが、逆になります。
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;
}
}
}
上記は、次のノード、または存在する場合は子ノードを返し、兄弟または子がもう存在しないが、1 レベルの深さしかない場合は親ノードを返します。HTML リストは無制限の深さにすることができるので、何らかの再帰が必要になるのでしょうか? これは、私のスキルが私を連れて行くことができる限りです。このリストを同じ方法で逆の順序で作業するために、「前の」リンクについても考え始めていません。
私はdevshedで同じことを尋ねました(数週間前)が、返事がありません.
回答ありがとうございます。
忍者、私はあなたのものを実装して成功しました。ネストされたリストを非常にうまく上下に移動できるようになりました。
さらに質問です。よろしければ、ツリー内のある点で「位置」を開始する機能が必要です。ユーザーは、ハッシュ (#post9 など) を使用してツリー内のノードを選択できます。リスト内の任意のノードをクリックして選択するか、そのノード独自のハッシュを含む URL をブックマークすることができます。
私のさらなる質問は、URL のハッシュを使用して、ツリー内のノードを見つけてその位置を取得するにはどうすればよいでしょうか? URL のハッシュは、li ノードの ID と相関しています。