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

时间:2019-06-04 21:45:22

标签: javascript jquery html wordpress 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标题时,因此我没有继续处理finish标签等。我不知道ul / li标签的自动关闭是由jQuery中的替换还是由Wordpress引起的(以前有一些自动关闭标签的问题)。

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

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用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>