[英]Create dynamic menu with javascript
我尝试用我相当薄弱的 javascript 技能创建一个菜单。
我的 html 页面如下所示:
<html>
<head>
...
</head>
<body>
<article class="article">
<h2>Title 1</h2>
<h2>Title 2</h2>
<h2>Title 3</h2>
</article>
</body>
</html>
我的脚本:
var allH2 = Array.from(document.querySelectorAll("h2"));
var article = document.querySelector("article");
document.body.onload = addMenu;
function addMenu () {
var menu = document.createElement("div");
menu.setAttribute("class", "menu");
var menu_title = document.createElement("h2");
var title = document.createTextNode("Menu");
menu_title.appendChild(title);
menu.appendChild(menu_title);
var list = document.createElement("ul");
list.setAttribute("class", "list");
menu.appendChild(list);
allH2.forEach(function callback(element, index) {
var link = document.createElement("a");
var content = document.createTextNode(element.textContent);
var list_element = document.createElement("li");
var href_el = document.querySelectorAll("h2")[index].href;
list_element.setAttribute("class", "list-element");
link.setAttribute("href", href_el);
link.appendChild(content);
list_element.appendChild(link);
list.appendChild(list_element);
});
document.body.insertBefore(menu, article);
}
问题是forEach
中的.href
返回我undefined
,然后链接不起作用。
PS:对不起,我的英语水平比较低:'c
此行将尝试从它没有的 h2 标记中获取链接:
var href_el = document.querySelectorAll("h2")[index].href;
如果您希望能够单击链接并滚动到页面的该部分,您可以使用 js 或 url 片段。 为简单起见,我建议使用 url 片段。
url 片段链接将滚动到具有相应 id 的项目(具有href="#thediv"
的元素将滚动到具有id="thediv"
的元素)
你可以试试这个:
var href_el = '#htwo' + index;
document.querySelectorAll("h2").id = 'htwo' + index;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.