使用jQuery为博客生成目录

这段代码展示了如何为div#content中的内容生成目录,也无非是对h系列标记进行解析。当然,也早有一些人实现了。
​1. [代码][HTML]代码     
<html>
    <head>
        <title> 测试  </title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <script type="text/javascript" src="../lib/js/jquery-1.7.1.min.js"></script>
    </head>
    <body>
        <script type="text/javascript">
            $(document).ready(function() {
                //index01
                $("#index01").text($("#content").html());
                //index02
                x = $("h1,h2").toArray();
                c = "";
                for (i = 0; i < x.length; i++)
                {
                    c = c + x[i].innerHTML + "<br />";
                }
                $("#index02").html(x + "<br/>" + c);
                //index03
                x = $("h1,h2");
                c = "";
                x.each(function() {
                    c = c + $(this).text() + "  " + $(this).prop('tagName') + "<br/>"; //prop()与attr()的区别
                });http://www.huiyi8.com/hunsha/lifu/​
                $("#index03").html(c);
                //index04
                //generate anchor
                x = $("h1,h2");
                n = 0;
                c = "";
                x.each(function() {
                    $(this).before("<a name='anchor" + n + "'></a>");
                    if ($(this).prop('tagName') == "H1") //不可用"h1"
                    {婚纱礼服欣赏        
                        c=c+"<a href='#anchor"+n+"' class='anchor-h1'>"+$(this).text()+"</a><br/>";
                    }
                    else {
                        c=c+"<a href='#anchor"+n+"' class='anchor-h2'>"+$(this).text()+"</a><br/>";
                    }
                    n = n + 1;
                });
                $("#index04").html(c);
            });
        </script>
        <div id="index01"></div><hr/>
        <div id="index02"></div><hr/>
        <div id="index03"></div><hr/>
        <div id="index04"></div><hr/>
        <div id="content">
            <h1>第一章</h1>
            <h2>第1节</h2>
            <p>你好</p>
            <h2>第2节</h2>
            <h1>第二章</h1>
            <h2>第1节</h2>
            <h2>第2节</h2>
        </div>
    </body>
</html>

2. [图片] 01.jpg    

posted @ 2014-09-09 16:37  虚空之眼  阅读(304)  评论(0编辑  收藏  举报