0

最初,我生成了一个dropdown menu

我添加了有关如何制作下拉菜单的更多详细信息。

        <div class="well sidebar-nav">
            <img src="building.gif" style="display: block;margin-left:auto; margin-right:auto;max-width:100%; max-height:100%;" />
            <div class="dropdown" style="padding-left: 20px; padding-top:5px;">
                <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" style="display: block;margin-left:auto; margin-right:auto;">
                    Select A Building
                    <span class=" caret">
                    </span>
                </button>

                <ul id="myul" class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1"></ul>

            </div>
        </div>
    </div><!--/span2-->

现在,我编写了以下代码:

    var buildingList=[
          {
            "BuildingName": "Adler Journalism and Mass Communication Building",
            "BuildingNumber": "0456"
          },
          {
            "BuildingName": "Art Building",
            "BuildingNumber": "0021"
           } 
    ];

    <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" style="display: block;margin-left:auto; margin-right:auto;">
                        Select A Building
                        <span class=" caret">
                        </span>
                    </button>
    <ul id="myul" class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
    </ul>

     <script type="text/javascript">
      var out = "";
      var ul = document.getElementById("myul");
      for (i = 0; i < buildingList.length; i++) {
                out = ' <li role="presentation"><a role="menuitem" tabindex="-1" href=" ' + buildingList[i].BuildingName + '  "> ' + buildingList[i].BuildingName + '   </a></li>';
                 var li = document.createElement("li");
                 var t = document.createTextNode(out);
                 li.appendChild(t);
                 ul.appendChild(li);
    }
    </script>

我想dropdown根据buildingList数组动态生成一个列表javascript,你能帮帮我吗?

提前致谢!

4

2 回答 2

0

你可以尝试这样的事情。

$.each(buildingList, function (index, value) {
    $(".dropdown-menu").append($("<li>").text(value.BuildingName));
})

我创建了一个小提琴,以便您可以看到。

https://jsfiddle.net/bcub7wsL/1/

我改变了小提琴,使它只使用普通的 Javascript

http://jsfiddle.net/ha80r95b/

于 2015-03-02T05:41:15.370 回答
-1

您可以拆分数组并将元素附加到下拉列表。我想这会对你有所帮助。

https://css-tricks.com/dynamic-dropdowns/

于 2015-03-02T04:54:09.343 回答