Преобразование всех заголовков страницы в список - PullRequest
0 голосов
/ 05 июня 2019

Прямо сейчас я борюсь с некоторыми довольно простыми 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>

Into:

<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 и оформить их в виде списка, но это не совсем то, что я ищу.В любом случае, я заинтересован в поиске решения для этого.

Заранее спасибо.

1 Ответ

1 голос
/ 05 июня 2019

Вы можете использовать jquery nextuntil (https://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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...