How auto-generate a table of contents

南笙酒味 提交于 2019-12-25 02:42:09

问题


I'm new to JavaScript, and for school I have to automatically make every <\h1> on my page generate into an "ol" with in every "li" a link to the place on my page where that header is placed so in the end I have a table of contents with links on every "li". So I should be able to just write text and not worry about the table of contents. Is there a way to do this without using too complixated code? And preferably not very long so I can understand it.

e.g.

<h1 id="h1-01">Title 1<\h1>
<h1 id="h1-02">Titel 2<\h1>
<h1 id="h1-03">Titel 3<\h1>
<h1 id="h1-04">Titel 4<\h1>

Make this generate like:

<ol>
<li><a href="h1-01">Title 1</a></li>
<li><a href="h1-02">Title 2</a></li>
<li><a href="h1-03">Title 3</a></li>
<li><a href="h1-04">Title 4</a></li>
</ol>

edit: I don't want anyone to make all of my homework, this is just a tiny tiny part of the homework even. What I want to know is how do I make an organized list with list items in javascript without too complicated code. I already found a way to put every header text in a variable. This is what I have

function generate(){
var titels = new Array();
for(var i = 1;i<10;i++){
var test = 'h1-0'+ i;
    titels[i] = document.getElementById(test).textContent;  
}
}
-->
</script>

The only problem is now that I have to make a list with these variables, but I haven't found anything usefull on the internet, everything that I've found uses Jquery ir is specific for someone's problem. I would also like a way to count the amount of headers I'm using but tthat's another question. Is it actually even possible to have code that gets literally implemented like I'm writing it?

like:

html.write("<ol>");

for(var i = 1, i<10,i++){

html.write("<il>" + titels[i] +  "<\il>");

}

html.write("<\ol>")

回答1:


I'm not going to do your homework, but will point you in a good direction.

Try building an object containing the id and the title of each entry. From there, you can use that object to build practically anything, including an ordered list.

Of course, you can hard-rewrite the h1 tags into list items, but that's just not the proper way to do it and not something you should learn from.




回答2:


A start hint: You could do it with the help of jquery.

Like this HTML:

 <ol id=contents></ol>

   <h1>Test</h1>
      bla bla 

      <h1> Test2 </h1>
      Ble ble ble

Jquery:

 $(document).ready(function(){
     $("h1").each(function(){
         $("#contents").append("<li>" + $(this).html() + "</li>");
     });
 });


来源:https://stackoverflow.com/questions/20304440/how-auto-generate-a-table-of-contents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!