如何自动生成目录 [英] How auto-generate a table of contents

查看:75
本文介绍了如何自动生成目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaScript的新手,在学校里,我必须自动将页面上的每个< \ h1>生成为一个"ol",并在每个"li"中添加指向页面上该标头位置的链接被放置在最后,我有一个目录,每个"li"上都有链接.因此,我应该能够只写文本,而不必担心目录.有没有办法在不使用过于复杂的代码的情况下做到这一点?而且最好不要太长,这样我才能理解.

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.

例如

<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>

使此生成类似:

<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>

我不希望任何人都做我的所有作业,即使这只是作业的一小部分.我想知道的是如何在没有太复杂的代码的情况下使用javascript中的列表项创建一个有组织的列表.我已经找到了一种将每个标题文本放入变量的方法. 这就是我所拥有的

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>

唯一的问题是我现在必须用这些变量列出一个列表,但是我没有在互联网上找到任何有用的东西,我发现所有使用Jquery ir的东西都是针对某个人的问题的.我还想一种方法来计算我正在使用的标头的数量,但这是另一个问题.实际上甚至有可能像我在写代码时那样实现代码吗?

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?

喜欢:

html.write("<ol>");

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

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

}

html.write("<\ol>")

推荐答案

开始提示: 您可以借助jquery来做到这一点.

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

喜欢此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>");
     });
 });

这篇关于如何自动生成目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆