Javascript body OnClick

后端 未结 3 1154
攒了一身酷
攒了一身酷 2021-02-20 13:33

I\'m in the process of learning Javascript and I\'m trying to create a simple dropdown menu. An example of my desired functionality can be seen on the google homepage in the top

3条回答
  •  粉色の甜心
    2021-02-20 13:58

    It looks like you have a pretty decent setup as-is. You'll likely run into some event bubbling problems (for more info, take a look at PPK's Event Order Article). That seems to be outside of the scope of your current question, so I'll just give you what you asked for:

    hideMenus()
    {
        var uls = document.getElementsByTagName('ul'), i;
        for (i = 0; i < uls.length; i++)
        {
            if (uls[i].className === 'submenu' && uls[i].style.display !== 'none')
            {
                uls[i].style.display = 'none';
            }
        }
    }
    

    First, we get all the

      's on the page. Then, we loop through all of them, check to see if it's a submenu, and if it's currently displayed. If both are true, then we hide it.

      There are a couple faults with this code:

      • If the uls have more than one class (class="animal submenu"), then it will not hide the menu
      • It will look through all the
          's on the page. This isn't exactly efficient, but it's the only way to do it without cross-browser support for getElementsByClass.

        These aren't huge faults, especially if you're only using this to learn about javascript, and if you closely control your code (i.e. no other developers are working on it). All in all, it's a good stepping stone.

        In the future, I'd suggest using addEvent - a fairly common function that allows you to add event handlers to elements without using onclick="...". There are a couple different implementations of it, but they (almost) all work the same from your perspective. Here are links to Dean Edwards's Version and John Resig's Version

        Good luck!

提交回复
热议问题