动态更改 javascript 中的按钮下拉列表?

Dynamically change a button-drop list in javascript?

尝试从 Bootstrap HTML 结合 Javascript 创建可更改的下拉按钮。 HTML 看起来像:

<div class="btn-group">
  <a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
    Menu
    <span class="caret"></span>
  </a>
  <ul class="dropdown-menu">
    <li><a href="#">Choice1</a></li>
    <li><a href="#">Choice2</a></li>
    <li><a href="#">Choice3</a></li>
    <li class="divider"></li>
    <li><a href="#">Choice..</a></li>
  </ul>
</div>

希望能够根据页面上发生的其他情况更改下拉按钮的选项。因此,如果用户单击页面上某处的 "profile" 按钮而不是 Choice1、Choice2 和 Choice3,则会出现 Resume、Contact Info、Education 等。菜单中的项目数量将发生变化,显示的确切值也会发生变化文本。理想情况下希望使用某种类型的数组来 push/pop 从选择。尝试过 add、childappend 等

这是一种方法 - 将所有菜单项都放在 HTML 中,然后使用 CSS 到 hide/show 适当的菜单项

<div class="btn-group">
    <a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
        Menu
        <span class="caret"></span>
    </a>
    <ul id='my-dropdown' class="dropdown-menu" data-menu-id='default'>
       <li class='default'><a href="#">Choice1</a></li>
       <li class='default'><a href="#">Choice2</a></li>
       <li class='default'><a href="#">Choice3</a></li>
       <li class="divider"></li>
       <li class='default'><a href="#">Choice..</a></li>
       <li class='profile'><a href="#">Resume</a></li>
       <li class='profile'><a href="#">Education</a></li>
       <li class='badgers'><a href="#">Eat a badger</a></li>
    </ul>
</div>

CSS:

/* hide all menu items */
ul.dropdown-menu > li {
    display: none; 
}

/* show menu items if they're relevant */
ul.dropdown-menu[data-menu-id=default] > li.default, 
ul.dropdown-menu[data-menu-id=profile] > li.profile, 
ul.dropdown-menu[data-menu-id=badgers] > li.badgers {
   display: list-item;
}

现在使用 javascript 更改下拉菜单中的 data-menu-id 属性,菜单项将自动更改:

var dropdownMenu = document.getElementById('my-dropdown');
dropdownMenu.setAttribute("data-menu-id", "profile");

有很多其他方法可以做到这一点,但这可能是最巧妙的方法。 CSS 基本上表示 "if the class of the list item matches the menu id attribute on the parent, make it visible".

这种方法的一个优点是你可以让一个菜单项在多个不同的菜单中可见,只需给它多个 类:

<!-- will be visible in the 'profile' menu and the 'badger' one -->
<li class='profile badgers'><a href="#">Badger Resume</a></li>