ネストされたol要素の子リストに親リストの番号を振る

Ads

Result

jQuery

$(document).ready(function() {
    if ($('ol:first').css('list-style-type') != 'none') { /* For IE6/7 only. */
        $('ol ol').each(function(i, ol) {
            ol = $(ol);
            var level1 = ol.closest('li').index() + 1;
            ol.children('li').each(function(i, li) {
                li = $(li);
                //子階層に親階層のナンバーを振る
                var level2 = level1 + '.' + (li.index() + 1);
                span要素でナンバリング
                li.prepend('<span>' + level2 + '</span>');
            });
        });
    }
});

css

ol{margin:15px;}
html>/**/body ol { /* Won't be interpreted by IE6/7. */
                list-style-type: none;
                counter-reset: level1;
            }
            ol li:before {
                content: counter(level1) ". ";
                counter-increment: level1;
            }
            ol li ol {
                list-style-type: none;
                counter-reset: level2;
            }
            ol li ol li:before {
                content: counter(level1) "." counter(level2) " ";
                counter-increment: level2;
            }
            ol li span { /* For IE6/7. */
                margin: 0 5px 0 -25px;
            }

html

<ol>
            <li>List</li>
            <li>List
                <ol>
                    <li>List</li>
                    <li>List</li>
                    <li>List</li>
                </ol>
            </li>
            <li>List</li>
            <li>List</li>
        </ol>

via

Number nested ordered lists in HTML