使用jQuery自动链接页面中的章节?

时间:2013-04-09 20:13:58

标签: jquery css automation article

相关网页:http://wlvrtn.com/sites/nms-chapters/page.php

此页面目前由3章组成,每章都包含在自己的文章标签中。将来,我将添加其他章节文章,以及浮动章节导航中的章节链接。

我想要实现的目标:

我想通过jQuery自动化章节导航链接目的地,这样列表中的第一个链接指向页面上的第一篇文章,第二个链接指向第二篇文章,依此类推。

即如果我添加第四章文章,我不想给它提供id“article-04”;我希望在添加章节nav中的第四个链接,知道它应该指向新文章。我猜这个“n-child”就是这个,但我太新了,不知道。

谢谢, XO


章导航:

<nav id="chapters">
  <ul>
     <li><a href="#">Chapter One</a></li>
     <li><a href="#">Chapter Two</a></li>
     <li><a href="#">Chapter Three</a></li>
  </ul>
</nav>

章节文章:

<article class="clearfix">
  <h1>Chapter One</h1>
</article>
<article class="clearfix">
   <h1>Chapter Two</h1>
     <p>And so on...</p>

3 个答案:

答案 0 :(得分:1)

这样的事情(demo)怎么样?

$(function(){

    // find the nav & headers
    var nav = $('#chapters li a'),
        articles = $('#main article > h1');

    // now assign an id/href to each
    nav.each(function(i){
        nav.eq(i).attr('href', '#article-' + i);
        articles[i].id = 'article-' + i;
    });

});

答案 1 :(得分:0)

有很多关于jquery的锚链接滚动的jquery教程。 我个人在我的一个项目中使用这个

尝试本教程:

http://tympanus.net/codrops/2011/12/05/lateral-on-scroll-sliding-with-jquery/

:)

答案 2 :(得分:0)

满足您的要求的一种相对简单的方法就是这样,尽管它当然可以优化:

$('h1').each(
    function(){
        var that = $(this),
            txt = that.text();
        that[0].id = txt.replace(/\s+/,'');

        if (!$('#toc').length){
            $('<ul />', { id : 'toc' }).prependTo('body');
        }

        var li = $('<li />').appendTo('#toc');
        $('<a />', {'href' : '#' + that.text().replace(/\s+/,''), text : that.text()}).appendTo(li);
    });

JS Fiddle demo

参考文献: