根據網頁的h2, h3標題自動產生目錄
如題,範例。
<!DOCTYPE html> <html> <body> <p id="tableOfContents"></p> <h2>Chapter</h2> <br><br><br> <h3>Section</h3> <br><br><br> <h3>Section</h3> <br><br><br> <h2>Chapter</h2> <br><br><br> <h3>Section</h3> <br><br><br> <h3>Section</h3> <br><br><br> <script> var allTitles = document.querySelectorAll("H2, H3"); var numberOfTitles = allTitles.length; var toc = ""; for(t=0, c=0, s=0; t < numberOfTitles; t++) { if(allTitles[t].nodeName == "H2") { c++; allTitles[t].setAttribute("id", "chapter" + c); s=0; toc += "<a href=#chapter" + c + ">"; toc += c + ". " + allTitles[t].innerHTML; toc += "</a>"; toc += "<br>"; } if(allTitles[t].nodeName == "H3") { s++; allTitles[t].setAttribute("id", "section" + c + "." + s); toc += " <a href=#section" + c + "." + s + ">"; toc += c + "." + s + ". " + allTitles[t].innerHTML; toc += "</a>"; toc += "<br>"; } } document.getElementById("tableOfContents").innerHTML = toc; </script> </body> </html>
No comments:
Post a Comment