2016-04-04 2 views
0

Я долгое время занимался поиском в googling и stackoverflow, и я застрял.
Задача заключается в следующем: сделать вложенную нумерацию (1., 1.1., 1.1.1 и т.д.) и для заголовков (<h2> через <h4>) и списки (<ol> и <ul>). Осложняющие пункты:Вложенная нумерация заголовков и списков

  1. там может быть заголовки и списки в любом количестве (например, один h2 может иметь три вложенные ol сек, второй h2 может иметь два h3 с, то первым h3 имеет два h4 сек , второй из которых имеет ul с вложенным ol и т. д. и т. д.). И нумерация должна быть уникальной и наблюдаться по всему документу.
  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(".") + ". "); 
}); 
Смежные вопросы