How to create a menu using only javascript code

谁说胖子不能爱 提交于 2021-02-08 10:13:07

问题


Ever since I started programming on NetBeans, I had to create a HTML menu for every page that I used which is starting to be very time-consuming because if I have many pages, I have to go back and edit back each to be updated. This is how my menu looks at the moment with HTML:

            <ul class="sidebar-menu">
            <li class="header">MAIN NAVIGATION</li>
            <li class="treeview active">
            <a href="#">
                <i class="fa fa-edit"></i> <span>Projects</span>
                <i class="fa fa-angle-left pull-right"></i>
            </a>
            <ul class="treeview-menu">
                <li class="active"><a href="offers.html"><i class="fa fa-circle-o"></i>Offers</a></li>
                <li class="active"><a href="mobilecarriers.html"><i class="fa fa-circle-o"></i>Mobile Carriers</a></li>
                <li class="active"><a href="affiliatepixel.html"><i class="fa fa-circle-o"></i>Affiliate Pixel Tracking</a></li>
                <li class="active"><a href="carrierip.html"><i class="fa fa-circle-o"></i>Carrier IP</a></li>
                <li class="active"><a href="UpdtConvStats.html"><i class="fa fa-circle-o"></i>Update Conversion Status</a></li>
                <li class="active"><a href="GetConvData.html"><i class="fa fa-circle-o"></i>Get Conversions Data</a></li>
                <li class="active"><a href="UpdtConv.html"><i class="fa fa-circle-o"></i>Update Conversions P/R</a></li>
            </ul>
            </li>
        </ul>

Now in order to avoid having a repeated menu on all pages, I want to create a menu using only Javascript code. I have already tried to build but it doesn't exactly reach the objective that I am aiming; for example: I need to have icons before the text and all it shows is a DOT for all of them, I also need to create sub-menus but I haven't exactly found a way to do it. Can anyone tell me if this code works for my purpose? If not, can anyone help me please?

(function(){

var dirs=window.location.href.split('/'),
cdir=dirs[dirs.length-2];

var dir_ofertas = "";
var dir_teste = "";

if (cdir === "Ofertas") {
    dir_teste = '../teste/';      
}

else if (cdir === "teste") {
    dir_ofertas = '../Ofertas/';        
}
var navItems = [
    {href: dir_ofertas + 'offers.html', text: 'Offers'},
    {href: dir_ofertas + 'mobilecarriers.html', text: 'Mobile Carriers'},
    {href: dir_teste + 'index.html', text: 'Test'}
];

var navElem = document.createElement("nav"),
    navList = document.createElement("ul"), 
    navItem, navLink;

navElem.appendChild(navList);

for (var i = 0; i < navItems.length; i++) {
    navItem = document.createElement("li");
    navLink = document.createElement("a");
    navLink.href = navItems[i].href;
    navLink.innerHTML = navItems[i].text;
    navItem.appendChild(navLink);
    navList.appendChild(navItem);
}
navList.children[0].className = "current";

window.onload = function () {
    document.getElementById('leftNav').appendChild(navElem);
};

}());

回答1:


you can use .innerHtml or .html (jquery) to inject html into a document for example

you could make code that goes through and generates html then injects it into a page (this for a webpage? or application?)

now problem with the above method is that the CSS wont work on it correctly sometimes.

lastly, I would suggest looking into php. On a project, I used php to call a python script whos output is a dropdown menu, making a dynamic dropdown menu of all items i had.

Edit: forgot to ask, is this a one time thing? generating the menu, or does this need to be regenerated on the fly?




回答2:


I recommend you to use jquery; it makes all the javascript generated web content much easier and readable, plus is not hard to learn. As an example, you could create an object that contains all the DOM elements before they exist in the DOM

var myButton=$('<div class="button">ventas</div>');

You can make whatever jQuery operation you want with this, such as

myButton.addClass('red');
myButton.append('myMenu');

therefore, you could make a function that converts a json into a menu

menu=[
   {
     name:"inicio",
     url:"http://www.cl"
   }
]

and so on. Just an idea. Then your object structure could look like

myMenu=[
   {
      name:"inicio",
      $element=('<div id="menu-inicio-0" class="top-menu">inicio</div>');
   },
   {
      name:"cuenta",
      $element=('<div id="menu-inicio-0" class="top-menu">inicio</div>'),
      children=[

          {
           name:"password",
           $element=('<div id="menu-inicio-0" class="top-menu">inicio</div>'),
        },
        {...}

      ]
   }
]

In jquery, you can add click listeners to each element, as said, even before added to DOM (only if you refer to the element by using it's carrying variable, no Id or Class calls)

for each button{
   $thisButton.on("click",function(){
      showSubMenuOrFollowLink();
   });
}

You can take a similar approach with vanilla javascript, but of course that is much harder. Over all, I recommend you to explore the possibility of having objects for each button, that have the DOM element as a variable, so you can refer to them easily.

hope this helps!



来源:https://stackoverflow.com/questions/37674396/how-to-create-a-menu-using-only-javascript-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!