【问题标题】:jQuery automatic heading numberingjQuery自动标题编号
【发布时间】:2017-04-12 22:42:12
【问题描述】:

我在网站上有 10-15 个 H2 标签字幕的文章。喜欢这样的东西。

<h1>Name of article</h1>
<h2>Subtitle</h2>
<p>.....</p>
<h2>Subtitle</h2>
<p>.....</p>
<h2>Subtitle</h2>
<p>.....</p>
<h2>Subtitle</h2>
<p>.....</p>

那么,问题是如何通过 jQuery 以降序自动为每个 H2 标签(字幕)指定编号?

<h1>Name of article</h1>
<h2>15.Subtitle</h2>
<p>.....</p>
<h2>14.Subtitle</h2>
<p>.....</p>
<h2>13.Subtitle</h2>
<p>.....</p>
<h2>12.Subtitle</h2>
<p>.....</p>

我知道如何通过 CSS 计数器来实现,但文章可以包含不同数量的字幕。我检查过类似的Automatic Numbering of Headings H1-H6 using jQuery 主题,但这不是我想要的。

【问题讨论】:

    标签: jquery automation html-heading css-counter


    【解决方案1】:

    您可以使用each 函数倒数。

    allItems = $("h2").length;
    $("h2").each(function (index){
      $(this).prepend(allItems - index + ". ");
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <h1>Name of article</h1>
    <h2>Subtitle</h2>
    <p>.....</p>
    <h2>Subtitle</h2>
    <p>.....</p>
    <h2>Subtitle</h2>
    <p>.....</p>
    <h2>Subtitle</h2>
    <p>.....</p>

    【讨论】:

      【解决方案2】:

      这应该会有所帮助

      var h2Elements = $('.content').find('h2');
      var h2ElemCount = h2Elements.length;
      $(h2Elements).each(function(i) {
        $(this).prepend(h2ElemCount - i + '. ');
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
      <div class="content">
        <h1>Name of article</h1>
        <h2>Subtitle</h2>
        <p>.....</p>
        <h2>Subtitle</h2>
        <p>.....</p>
        <h2>Subtitle</h2>
        <p>.....</p>
        <h2>Subtitle</h2>
        <p>.....</p>
      </div>

      【讨论】:

      • 谢谢!这正是我想要的。我刚刚放了文章标签而不是 .content 类。
      • 还有一个问题:如何添加一些 CSS 类来风格化?我尝试使用 .addClass('.h2style');但它不起作用。
      • 无需输入'.' (句号)在addClass里面,你可以做.addClass('h2style')
      • 也许,你能帮忙解决另一个问题吗? stackoverflow.com/questions/43397234/…
      【解决方案3】:

      试试这个:

      var h2Length = $("h2").length;
      $("h2").each(function(i,obj) { 
        $(obj).html(h2Length +". "+$(obj).html());
        h2Length--; 
      });
      

      【讨论】:

      • 谢谢@Tanmay!
      猜你喜欢
      • 2011-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-12
      • 1970-01-01
      • 2017-04-17
      • 2012-04-02
      • 1970-01-01
      相关资源
      最近更新 更多