开发者

Jquery OL auto numbering

开发者 https://www.devze.com 2023-01-07 20:04 出处:网络
I\'m trying to create auto numbering OL list with JQu开发者_如何转开发ery. I want to create list lik this

I'm trying to create auto numbering OL list with JQu开发者_如何转开发ery. I want to create list lik this

  1. apple

    1.1 green apple

    1.2 red apple

    1.3 red apple

  2. orange

    2.1 orange juice

    2.2 etc

Help me to create this please)

   $('#content-main-text ol:first-child li').each(function(index) {
     $(this).html((index + 1) + '. ' + $(this).html());
   });

This code adds number for all LI in my list...


I though it would be easy to find a css property to provide the functionality you want, but I couldn't find anything. This is how you do it with jQuery (but it has some issues):

function fn(li,parentPrefix) {
    $(li).children("li").each( function(index) {
        var i = index + 1;
        var myPrefix = parentPrefix ? parentPrefix + "." + i : i;
        $(this).html(myPrefix + " " + $(this).html());
        fn( $(this).children("ol"), myPrefix);
    });
}

var topmostOLs = $("ol").filter(function() { return !$(this).parent().is("li") } )
topmostOLs.each(function() {
    fn(this);
});

It finds all topmost ol elements and the recursively visits their child lists to add the numbering.

For this to display correctly you have to add the css ol { list-style: none } to remove the native css-numbering.

One problem with this is that if you mark the list and copy it, it will copy both the added numbering and the native numbering of the ol.

Here's a demo: http://jsbin.com/utuci3/edit (press preview at the top left to view the result)

0

精彩评论

暂无评论...
验证码 换一张
取 消