繁体   English   中英

将页面的所有标题转换为列表

[英]Converting all headings of a page into a list

现在,我正在使用一些非常基本的jQuery(不要讨厌我)。 我的目标是将页面的每个h3 / h4标头转换为列表,以进行“自创建”侧边栏导航。

例如:

<h3>This is a header</h3>
    <h4>This is its subheader</h4>
       <p>Here's some explanation.<p>
    <h4>This is another subheader</h4>
       <p>Here's some explanation.<p>
<h3>Here is a new header</h3>
    <h4>With</h4>
       <p>Here's some explanation.<p>
    <h4>some</h4>
       <p>Here's some explanation.<p>
   <h4>other</h4>
       <p>Here's some explanation.<p>
   <h4>subheaders</h4>
       <p>Here's some explanation.<p>

成:

<ul>
  <li>This is a header
    <ul>
      <li>This is its subheader</li>
      <li>This is another subheader</li>
    </ul>
  </li>
  <li>Here is a new header
    <ul>
      <li>With</li>
      <li>some</li>
      <li>new</li>
      <li>subheaders</li>
    </ul>
  </li>
</ul>

到目前为止,我所做的是:

//Selecting all existing Headers and Subheaders of the content wrapper
var headers = $('.some-text-wrapper h3, .some-text-wrapper h4');

//Placing them into a new div (later sidebar)      
$('#headings').html(headers);

//Looping through each element trying to replace the tags
$('#headings h3, #headings h4').each(function(){
    if ( $(this).is(':first-child') ) {
        $(this).replaceWith('<ul><li>' + $(this).html() +'<ul>')
    } else if ( $(this).prop("tagName") == 'H3' ) {
        $(this).replaceWith('</ul></li><li>' + $(this).html() +'<ul>')
    } else {
        $(this).replaceWith('<li>' + $(this).html() +'</li>')
    }
});

不幸的是,我最终遇到了一些麻烦,例如:

<ul>
   <li>This is a header
   <ul></ul>
   </li>
</ul>
<li>This is its subheader</li>

当涉及到h3标题时,我就没有继续进行整理标签等的工作。我不知道ul / li标签的自动关闭是由jQuery替换还是由Wordpress引起的(有些自动关闭标签的问题)。

我知道我可以简单地使用创建的h3 / h4元素并将它们设置为列表样式,但这并不是我真正想要的。 无论如何,我有兴趣为此寻找解决方案。

提前致谢。

您可以使用jquery的nextuntilhttps://api.jquery.com/nextUntil/ )并将其传递给选择器和过滤器以创建适当的列表。

 var output = ""; $("h3").each(function(){ output += "<li>" + $(this).text() + "</li>"; if($(this).next("h4").length > 0){ output += "<ul>"; $(this).nextUntil("h3","h4").each(function(){ output += "<li>" + $(this).text() + "</li>"; }); output += "</ul>"; } }); $("#list").html(output); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h3>This is a header</h3> <h4>This is its subheader</h4> <p>Here's some explanation.<p> <h4>This is another subheader</h4> <p>Here's some explanation.<p> <h3>Here is a new header</h3> <h4>With</h4> <p>Here's some explanation.<p> <h4>some</h4> <p>Here's some explanation.<p> <h4>other</h4> <p>Here's some explanation.<p> <h4>subheaders</h4> <p>Here's some explanation.<p> <div id="list"><ul></ul></div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM