简体   繁体   中英

HTML\CSS\JavaScript: How can I build a menu dynamically?

I am using the W3.CSS animated drop-down ( https://www.w3schools.com/w3css/w3css_dropdowns.asp ).

But I cannot figure out how can I populate the menu items dynamically according to a list of item names.

I guess some Javascript should be involved here, so I try in this forum 🙂

 <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <div class="w3-dropdown-click"> <button onclick="showMenu()" class="w3-button">Team1</button> <div id="Demo" class="w3-dropdown-content w3-bar-block w3-animate-zoom"> <a href="#" class="w3-bar-item w3-button">Link 1</a> <a href="#" class="w3-bar-item w3-button">Link 2</a> <a href="#" class="w3-bar-item w3-button">Link 3</a> </div> </div> <script> async function getTeams() { try{ (async () => { const response = await fetch('http://localhost:8088/teams') var teamsArrObj = await response.json() console.log(teamsArrObj); return teamsArrObj; })() }catch{ console.log("error"); } } function showMenu() { var x = document.getElementById("Demo"); if (x.className.indexOf("w3-show") == -1) { x.className += " w3-show"; } else { x.className = x.className.replace(" w3-show", ""); } } </script>

Thanks!

Assuming that you're using a regular js array of text, you can loop over that array and insertAdjacentHTML into the dropdown.

for (let text of /*insert array name here*/) {
document.getElementById('Demo').insertAdjacentHTML('beforeend', `<a href="#" class="w3-bar-item w3-button">${text}</a>`

Here we use the modern for...of loop, and do insertAdjacentHTML. Check the MDN docs if you are not familiar with the function. We also use the ES6 template strings to insert.

Because W3 Schools has so much wrong in their demo that you've linked to, I've recreated their example (the right way) and shown how the CSS would be done (instead of relying on their pre-made CSS that you don't get to see).

You'll note that the actual hiding/showing of the menu is accomplished with a single line of JavaScript instead of all that outdated string related stuff that W3 Schools uses.

And, you'll see how you can dynamically load the menu items from an array of object data.

 <!DOCTYPE html> <html> <head> <title>W3.CSS</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> button { background-color:black; color:white; padding:5px; border:none; font-size:1.1em; /* 10% bigger than normal */ } #Demo { position:relative; box-shadow:0 0 20px #808080; padding:6px; margin-top:3px; height:auto; width:75px; transform-origin: center; /* Make effect work from center outward */ transition:all .5s; /* Make changes to all CSS happen over 1 second */ } /* The style of the menu when it's hidden */ #Demo.hidden { transform:scale(0,0); /* Scale it to 0 by 0 pixels */ } .menuItem { display:block; /* Each item on its own line */ text-decoration:none; /* no underline on the links */ padding:3px; font-family:Arial; } .menuItem:hover { background-color:#e0e0e0; } </style> </head> <body> <div> <h1>Animated Dropdown</h1> <div class="w3-dropdown-click"> <button>Click me</button> <div id="Demo" class="hidden"></div> </div> </div> <script> let items = [ { text: "Link 1", path: "https://example.com"}, { text: "Link 2", path: "https://hbo.com"}, { text: "Link 3", path: "https://cbs.com"}, ]; const demo = document.getElementById("Demo"); // Loop over the items array items.forEach(function(item){ // Create a new anchor element and configure it: let link = document.createElement("a"); link.classList.add("menuItem"); link.href = item.path; link.textContent = item.text; // Append the new link to the menu demo.appendChild(link); }); document.querySelector("button").addEventListener("click", function(){ demo.classList.toggle("hidden"); // Toggle the display of the menu }); </script> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM