0
私はグーグルとstackoverflowをかなり長時間行ってきましたが、私は立ち往生しています。
タスクは以下の通りである:両方の見出し(<h4>
スルー<h2>
)とリスト(<ol>
と<ul>
)のためのネストされた番号(1.
、1.1.
、1.1.1
等)を行います。複雑な点がある:見出しとリストのネストされた数値
- 任意の量の見出しやリスト(例えば、1
h2
を最初h3
は、2つのh4
Sを有し、第二h2
は、2つのh3
Sを有することができ、ネストされた3つのol
Sを有することができるがあるかもしれませんそれらのうちの2番目には、ol
などのネストされたul
などがあります)。番号はユニークであり、文書全体で確認する必要があります。 - 文書は、HTMLを使用していない人のためのテンプレートになるため、クラスやデータ属性などが少ないほどよいでしょう。
$(function() { indices = new Array(); // Not every element should be numbered, so I've added a class to those who should $(".item").each(function() { // I'm assigning the level manually, like this: // <h4 class="item" data-level="3">blah blah</h4> // any better solution is welcome var hIndex = parseInt($(this).data("level")); if (indices.length - 1 > hIndex) { indices= indices.slice(0, hIndex + 1); } if (indices[hIndex] == undefined) { indices[hIndex] = 0; } indices[hIndex]++; // Now I try to number lists and nested lists, and here I'm stuck if ($(this).is("ol, ul")) { var $that = $(this); $(this).find("li").each(function() { // Trying to add those attributes to <li>s... no dice :( $(this).addClass("item"); $(this).data("level", $that.data("level")+1); }); } var number = $.grep(indices, Boolean).join("."); $(this).prepend(number+". "); }); });
を任意の提案が高く評価されています。私はすでにやった
。