动态加载下拉框列表并添加onclick事件

时间:2020-12-16 14:34:03

1.  js动态加载元素并设置属性

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

  <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下拉框

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

<!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.  根据1、2可得到如下两段代码,获取后台返回数据,动态生成<li>标签

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代码

<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>