2016-04-04 6 views
0

私はグーグルとstackoverflowをかなり長時間行ってきましたが、私は立ち往生しています。
タスクは以下の通りである:両方の見出し(<h4>スルー<h2>)とリスト(<ol><ul>)のためのネストされた番号(1.1.1.1.1.1等)を行います。複雑な点がある:見出しとリストのネストされた数値

  1. 任意の量の見出しやリスト(例えば、1 h2を最初h3は、2つのh4 Sを有し、第二h2は、2つのh3 Sを有することができ、ネストされた3つのol Sを有することができるがあるかもしれませんそれらのうちの2番目には、olなどのネストされたulなどがあります)。番号はユニークであり、文書全体で確認する必要があります。
  2. 文書は、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+". "); 
        }); 
    }); 
    

    を任意の提案が高く評価されています。私はすでにやった

答えて

0

誰も私のようなものを必要としていない場合は、これは私が最後にそれを達成した方法です。すべての
まず、あなたは次のように項目(見出しやリスト)をマークする必要があります。

<h2 class="item" data-level="1">Largest item</h2> 
<h3 class="item" data-level="2">A smaller item</h3> 
<ol class="item" data-level="3"> 
<li>Smallest item 1</li> 
<li>Smallest item 2</li> 
<li>Smallest item 3</li> 
</ol> 

注:手動data-levelを設定する必要があり、私はこれまでと何もできませんでした。
コードはここに入れてください。$(function() {}

$("ol.item").each(function() { 
    // There might be lots of <li>s, we don't want to set the attributes manually for each one 
    $(this).find("li").each(function() { 
     $(this).addClass("item").data("level", $(this).parent().data("level")); 
    }); 
    $(this).removeClass("item"); // The <ol> does not need this anymore 
}); 

indices = new Array(); 
$(".item").not("ol").each(function() { // Just in case, we don't need <ol>s 
    var hIndex = parseInt($(this).data("level")); 
    // Going to the next level 
    if (indices.length - 1 > hIndex) { 
     indices= indices.slice(0, hIndex + 1); 
    } 
    // Going to the previous level 
    if (indices[hIndex] == undefined) { 
     indices[hIndex] = 0; 
    } 
    indices[hIndex]++; 
    // Cutting off nulls and prepending the number to the item 
    $(this).prepend($.grep(indices, Boolean).join(".") + ". "); 
}); 
関連する問題