-1

I have got a php file which uses an include function to import the article. The article is a php file. I would like to create a table_of_contents() function, which I place inside the file where I want a contents list to appear (like on Wikipedia articles). This function should scan the article for all <h2> tags with IDs beginning with "article-", and output a list of these headings as links.

Eg:

<h1>Article</h1>
<?php table_of_contents() ?>
<h2 id="article-intro">Introduction</h2>
<p>text</p>
<h2>Middle</h2>
<p>text</p>
<h2 id="article-conclusion">Conclusion</h2>
<p>text</p>

would render

<h1>Article</h1>
<ul>
    <li><a href="#article-intro">Introduction</a></li>
    <li><a href="#article-conclusion">Conclusion</a></li>
</ul>
<h2 id="article-intro">Introduction</h2>
<p>text</p>
<h2>Middle</h2>
<p>text</p>
<h2 id="article-conclusion">Conclusion</h2>
<p>text</p>
4

1 回答 1

2
<h1>Article</h1>
<ul Id="menu">

</ul>
<h2 id="article-intro">Introduction</h2>
<p>text</p>
<h2>Middle</h2>
<p>text</p>
<h2 id="article-conclusion">Conclusion</h2>
<p>text</p>


<script>
$('h2[id^="article-"]').each(function(){
$('#menu').append('<li><a href="#article-'+$(this).html()+'">'+$(this).html()+'</a></li>');
});
</script>

我认为这会奏效。不要忘记包含最新的 jquery。

于 2013-05-06T09:34:03.410 回答