【问题标题】:jQuery: How to add automatically LI elements from each heading in articlejQuery:如何从文章中的每个标题自动添加 LI 元素
【发布时间】:2016-08-23 14:22:58
【问题描述】:

我想在每篇博文中实现“ScrollSpy”(我使用 Materialize)。我认为最好的实现是使用 jQuery。但是,我正在努力使其动态化。所以,到目前为止我有这个代码。

$('body.single .entry-content').append('<div class="col hide-on-small-only m3 l2"><ul class="section table-of-contents"></ul></div>');

var h2 = $('.entry-content').find('h2').text();
var h3 = $('.entry-content').find('h3').text();

$('ul.table-of-contents').append("<li><a href='#" +h2 +"'>" +h2 +"</a></li>");
$('ul.table-of-contents').append("<li><a href='#" +h3 +"'>" +h3 +"</a></li>");

如何根据 h2、h3、h4 等的数量使其动态化?

【问题讨论】:

    标签: jquery wordpress post scrollspy


    【解决方案1】:

    您可以遍历标题元素,然后添加 li 元素,例如:

    var html = '';
    $('.entry-content').find('h2, h3, h4, h5').each(function() {
      var header = $(this).text();
      html += "<li><a href='#" + header + "'>" + header + "</a></li>";
    });
    $('ul.table-of-contents').append(html);
    

    【讨论】:

    • 完美无瑕。谢谢!
    【解决方案2】:

    你可以试试下面的块

    $('body.single .entry-content').append('<div class="col hide-on-small-only m3 l2"><ul class="section table-of-contents"></ul></div>');
    
    $(".entry-header h2, .entry-header h3").each(function (index) {
        var $this = $(this), ID = "header" + index;
        $this.attr("id", ID);
        $("ul.table-of-contents").append(
            $("<li/>").append($("<a/>").attr("href", "#" + ID).text(h2.text());
        );
    });
    

    【讨论】:

      【解决方案3】:

      未测试:

      假设你想升级到 h4

      For (var i=0;i<=4;i++){
      var hTag= 'h' + i.toString();
      hText=    $('.entry-content').find('hTag').text();
      $('ul.table-of-contents').append("<li><a href='#" +hText +"'>" +hText +"</a></li>");
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-11
        • 2012-03-21
        • 2014-07-14
        • 1970-01-01
        • 1970-01-01
        • 2015-05-11
        • 1970-01-01
        相关资源
        最近更新 更多