使用Javascript在导航栏中创建Li to UL

问题描述

我想构建一个动态导航栏,该导航栏在创建节时自动添加li,并在单击时有一个链接,该链接转到被单击的节。我写了一些代码,但是网页上什么也没显示。我也尝试使用foreach代替for,并且到目前为止也无法正常工作。

//global variable for ul
const navbarUl = document.getElementById(‘navbar__list’);

//global variable for sections
const sections = document.querySelectorAll(‘section’);
for(let i =1; i <= sections.length; i++) {

//defining variables

const fragment = document.createDocumentFragment();

const list =document.createElement('li');

const anchor = document.createElement('a');

let datanav = section.getAttribute('data-nav');

anchor.setAttribute('href',`"#section${sections.length}"`);
//appending

anchor.innerHTML = datanav;

anchor.classList.add('menu__link');

list.appendChild(anchor);

fragment.appendChild(list);
//eventlistener to scroll when clicked

const sections = document.querySelectorAll('section');

anchor.addEventListener('click',function(event){

    event.preventDefault()

    sections[i].scrollIntoView({behavior:"smooth"});

});

};
navbarUl.appendChild(fragment);
.navbar__menu ul {
  padding-left: 0;
  margin: 0;
  text-align: right;
}

.navbar__menu li {
  display: inline-block;
}

.navbar__menu .menu__link {
  display: block;
  padding: 1em;
  font-weight: bold;
  text-decoration: none;
  color: #000;
}

.navbar__menu .menu__link:hover {
  background: #333;
  color: #fff;
  transition: ease 0.3s all;
  list-style: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <Meta charset="UTF-8">
  <Meta name="viewport" content="width=device-width,initial-scale=1.0">
  <Meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Manipulating the DOM</title>
  <!-- Load Google Fonts -->
  <link href="https://fonts.googleapis.com/css?family=Fira+Sans:900|Merriweather&display=swap" rel="stylesheet">  <!-- Load Styles -->
  <link href="css/styles.css" rel="stylesheet">

</head>
<body>
  <!-- HTML Follows BEM naming conventions 
  IDs are only used for sections to connect menu achors to sections -->
  <header class="page__header">
    <nav class="navbar__menu">
      <!-- Navigation starts as empty UL that will be populated with JS -->
      <ul id="navbar__list"> </ul>

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)