jQuery實現標籤子元素的新增和賦值
阿新 • • 發佈:2019-02-13
一、在jsp頁面中定義<select>標籤,如下:
<div><span>科室:</span><select class="dept-name-show" style="width: 70%;"></select></div>
二、編寫js語句:
<script> $(function () { var dname = $(".dept-name-show").eq(0);//選定<select>標籤 var url = "${pageContext.request.contextPath}/getDepts.do";//請求路徑 $(".dept-name-show").click(function () { $.get( url, function (res) { var len = res.length; var op = dname.children().length; if (op < len) { varpp = "<option></option>"; for (var i = 0; i < len; i++) { dname.append(pp); dname.children().eq(i).text(res[i].name); } } } ) }) }) </script>
三、編寫對應的請求語句:
List<Dept> deptList=null; @RequestMapping(value = "/getDepts",method = {RequestMethod.GET}) public void getDepts(HttpServletResponse response) throws IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/json;charset=utf-8"); if (deptList == null){ deptList = deptService.findAllDepts(); }else { String res=JSON.toJSONString(deptList); response.getWriter().write(res); } }
四、實現效果如下: