動態加載下拉框列表並添加onclick事件

1.  js動態加載元素並設置屬性javascript

摘自(http://www.liangshunet.com/ca/201408/336848696.htm)css

  <div id="parent"></div>

  function addElementDiv(obj) {
    var parent = document.getElementById(obj);
    //添加 div
    var div = document.createElement("div");
    //設置 div 屬性,如 id
    div.setAttribute("id", "newDiv");
    div.innerHTML = "js 動態添加div";
    parent.appendChild(div);
  }
  調用:addElementDiv("parent");

2.  bootstrap下拉框html

摘自(http://www.w3cschool.cc/bootstrap/bootstrap-v2-dropdown-plugin.html)java

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Bootstrap dropdown with tabs and pills example</title>
    <link href="/twitter-bootstrap/twitter-bootstrap-v2/docs/assets/css/bootstrap.css" rel="stylesheet" type="text/css" />

</head>
<body>
    <ul class="nav nav-pills">
    <li class="dropdown all-camera-dropdown">
           <a class="dropdown-toggle" data-toggle="dropdown" href="#">
            Tutorials
               <b class="caret"></b>
           </a>
    <ul class="dropdown-menu">
            <li data-filter-camera-type="all"><a data-toggle="tab" href="#">HTML5</a></li>
            <li data-filter-camera-type="Alpha"><a data-toggle="tab" href="#">PHP</a></li>
            <li data-filter-camera-type="Zed"><a data-toggle="tab" href="#">MySQL</a></li>
            <li data-filter-camera-type="Bravo"><a data-toggle="tab" href="#">JavaScript</a></li>

     </ul>
</li></ul>
    <script type="text/javascript" src="/twitter-bootstrap/twitter-bootstrap-v2/docs/assets/js/jquery.js"></script>
    <script type="text/javascript" src="/twitter-bootstrap/twitter-bootstrap-v2/docs/assets/js/bootstrap-dropdown.js"></script>
   </body>
</html>

3.  根據一、2可獲得以下兩段代碼,獲取後臺返回數據,動態生成<li>標籤jquery

function addLiElement(obj)
    {
     //data爲後臺返回的數據   jQuery.getJSON('http://localhost:8080/adep/getModuleData', null, function(data) { var keys = data.key[0]; var s=document.getElementById(obj) for(var i=0 ; i
<keys.length ; i++) { var li = document.createElement("li"); var a = document.createElement("a"); li.appendChild(a); a.innerHTML = keys[i]; a.setAttribute("data-toggle","dropdown"); a.setAttribute("href","#"); s.appendChild(li); } }); } addLiElement("moduleul");

附html代碼bootstrap

<div class="navbar">
            <div class="container">
                <ul class="nav nav-pills">
                    <li class="dropdown all-camera-dropdown" id="accountmenu">
                        <a class="dropdown-toggle" data-toggle="dropdown" href="#">請選擇模塊<b class="caret"></b></a>
                        <ul class="dropdown-menu" id="moduleul">
                            <li data-filter-camera-type="all"><a data-toggle="tab" href="#">全部模塊</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
</div>
相關文章
相關標籤/搜索