Start a new numbered list using jQuery

<ul>
    <li>test</li>
    <li>test</li>
    <li>test</li>
    <li>test</li>
    <li>test</li>
    <li>test</li>
    <li>test</li>
</ul>

<script>
$(document).ready(function(){   
    var increment=3;
    var start=8;
    $("ul").children().each(function(i) {
        $(this).prepend('<tag>'+(start+i*increment).toString()+'.</tag>');
    });
});
</script>

Is there a way to start a new account for another ul list? With the code above, this is what I get!

<ul>
<li> test
<li> test
<li> test
<ul/>

Output

1. test
2. test
3. test

second list ul

<ul>
<li> test
<li> test
<li> test
<ul/>

Output

4. test
5. test
6. test

Instead of starting the second ul tag with 1. 2. 3. it continues to count using the first ul 5. 6. 7.

So, is it possible to reset count and run it again for another ul tag? If possible, how?

+3
source share
3 answers

Use an ordered list:

HTML

<ol id="num_list">
  <li>How</li>
  <li>Now</li>
  <li>Brown</li>
  <li>Cow</li>
</ol>

CSS

#num_list { list-style-type: decimal; }

EDIT : if you cannot use an ordered list, use JavaScript:

$(function() {
  $('ul').each(function() {
     $(this).children().prepend(function(index, html) {
        return '<span>' + (index+1) + '. </span>';
     });
  });
});

JsFiddle example

+2
source
$('ul').each(function() {
    $(this).children().each(function(i) {
        $(this).prepend('<span>' + (i + 1) + '.</span> ');
    });
});

Demo: http://jsfiddle.net/vSyK6/1/

+2
source
var increment = 1;
$('ul').each(function() {
    var ul = $(this),
        li = ul.find('> li'),
        ol = $('<ol />').attr('start', increment);
    ul.after(ol);
    ol.append(li);
    ul.remove();
    increment += li.length;
});

: http://jsbin.com/opuyi/3

, () :

1. One
2. Two
    4. Three
3. Four
0

Source: https://habr.com/ru/post/1787071/


All Articles