최근 작업에 트리 드롭다운 박스 컴포넌트가 필요하기 때문에 정보를 확인한 후 구현하는 방법은 일반적으로 두 가지가 있습니다. 하나는 zTree를 사용하여 구현하는 것이고, 다른 하나는 easyUI를 사용하여 구현하는 것입니다. 회사의 프런트 엔드는 easyUI를 사용하여 설계되지 않았기 때문에 드롭다운 트리를 구현하기 위해 zTree를 선택했습니다.
여기에서는 다음 Json과 유사한 간단한 데이터 형식(예: 간단한 Json 형식)이 사용됩니다.
var zNodes =[ {id:1, pId:0, name:"北京"}, {id:2, pId:0, name:"天津"}, {id:3, pId:0, name:"上海"}, {id:6, pId:0, name:"重庆"}, {id:4, pId:0, name:"河北省", open:true, nocheck:true}, {id:41, pId:4, name:"石家庄"}, {id:42, pId:4, name:"保定"}, {id:43, pId:4, name:"邯郸"}, {id:44, pId:4, name:"承德"}, {id:5, pId:0, name:"广东省", open:true, nocheck:true}, {id:51, pId:5, name:"广州"}, {id:52, pId:5, name:"深圳"}, {id:53, pId:5, name:"东莞"}, {id:54, pId:5, name:"佛山"}, {id:6, pId:0, name:"福建省", open:true, nocheck:true}, {id:61, pId:6, name:"福州"}, {id:62, pId:6, name:"厦门"}, {id:63, pId:6, name:"泉州"}, {id:64, pId:6, name:"三明"} ];
여기서 먼저 다음과 같이 발견된 해당 데이터를 캡슐화하기 위한 엔터티 빈이 필요합니다.
public class ZtreeNode { // id private String id; // 父id private String pId; // 显示名称 private String name; // 是否打开 (这里默认是不打开的,如果需要打开,设为true) // private boolean open ; // 能否选择 (设置节点是否能够选择,默认都能选择,设为true对应的节点不能选择) // private boolean nocheck ; /**getter and setter*/ }
여기서 주목해야 할 점은 pId의 두 번째 문자가 대문자라는 점입니다. 소문자로 쓰면 트리 구조로 구성할 수 없으며 모든 것이 루트 노드입니다.
그런 다음 데이터베이스에서 가져온 데이터를 해당 ztree에 필요한 Bean으로 변환한 후 해당 Json으로 변환합니다.
// 获取商品分类树 返回json public String getGoodsCategoryTreeJson() { List<GoodsCategory> allGoodsCategoryList = goodsCategoryService.getGoodsCategoryTreeJson() ; List<ZtreeNode> ztreelist = new ArrayList<ZtreeNode>(); for(GoodsCategory gcty : allGoodsCategoryList){ ZtreeNode treenade = new ZtreeNode(); treenade.setId(gcty.getId()); treenade.setpId(gcty.getParent()==null?"":gcty.getParent().getId()); treenade.setName(gcty.getName()); ztreelist.add(treenade); } return ajax(ztreelist); }
다음과 같이 목록을 해당 Json 메서드로 변환합니다.
사용된 Json 툴킷:
import org.springframework.base.util.JsonUtil; private static final String HEADER_ENCODING = "UTF-8"; private static final boolean HEADER_NO_CACHE = true; private static final String HEADER_TEXT_CONTENT_TYPE = "text/plain"; private static final String HEADER_JSON_CONTENT_TYPE = "text/plain"; // AJAX输出 protected String ajax(String content, String contentType) { try { HttpServletResponse response = initResponse(contentType); response.getWriter().write(content); response.getWriter().flush(); } catch (IOException e) { e.printStackTrace(); } return NONE; } // 根据文本内容输出AJAX protected String ajax(String text) { return ajax(text, HEADER_TEXT_CONTENT_TYPE); } // 根据操作状态输出AJAX protected String ajax(Status status) { HttpServletResponse response = initResponse(HEADER_JSON_CONTENT_TYPE); Map<String, String> jsonMap = new HashMap<String, String>(); jsonMap.put(STATUS_PARAMETER_NAME, status.toString()); JsonUtil.toJson(response, jsonMap); return NONE; } // 根据操作状态、消息内容输出AJAX protected String ajax(Status status, String message) { HttpServletResponse response = initResponse(HEADER_JSON_CONTENT_TYPE); Map<String, String> jsonMap = new HashMap<String, String>(); jsonMap.put(STATUS_PARAMETER_NAME, status.toString()); jsonMap.put(MESSAGE_PARAMETER_NAME, message); JsonUtil.toJson(response, jsonMap); return NONE; } // 根据Object输出AJAX protected String ajax(Object object) { HttpServletResponse response = initResponse(HEADER_JSON_CONTENT_TYPE); JsonUtil.toJson(response, object); return NONE; } // 根据boolean状态输出AJAX protected String ajax(boolean booleanStatus) { HttpServletResponse response = initResponse(HEADER_JSON_CONTENT_TYPE); Map<String, Object> jsonMap = new HashMap<String, Object>(); jsonMap.put(STATUS_PARAMETER_NAME, booleanStatus); JsonUtil.toJson(response, jsonMap); return NONE; } private HttpServletResponse initResponse(String contentType) { HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType(contentType + ";charset=" + HEADER_ENCODING); if (HEADER_NO_CACHE) { response.setDateHeader("Expires", 1L); response.addHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache, no-store, max-age=0"); } return response; }
이런 방식으로 프런트 데스크에서 요구하는 데이터를 라이브러리에서 꺼내 해당 Json에 캡슐화합니다.
다음 단계는 프런트엔드를 구현하는 것입니다. 프런트엔드에서 가져와야 하는 js와 css는 다음과 같습니다.
<link rel="stylesheet" href="${base}/template/ztree/css/demo.css" type="text/css"> <link rel="stylesheet" href="${base}/template/ztree/css/zTreeStyle/zTreeStyle.css" type="text/css"> <script type="text/javascript" src="${base}/template/ztree/js/jquery.ztree.core.js"></script>
여기에 있는 데모.css만 직접 추가했으며, 다른 것들은 공식적으로 공식화되었습니다. 다음과 같이 공식 데모에 사용된 CSS에서 수정되었습니다(여기에는 삭제되지 않은 중복 스타일이 있습니다). >
div.content_wrap {width: 400px;} div.content_wrap div.left{float: left;} div.content_wrap div.right{float: right;width: 340px;} div.zTreeDemoBackground {text-align:left;} ul.ztree {margin-top: 10px;border: 1px solid #617775;background: #fefefe;width:220px;height:360px;overflow-y:scroll;overflow-x:auto;} ul.log {border: 1px solid #617775;background: #f0f6e4;width:300px;height:170px;overflow: hidden;} ul.log.small {height:45px;} ul.log li {color: #666666;list-style: none;padding-left: 10px;} ul.log li.dark {background-color: #E3E3E3;} /* ruler */ div.ruler {height:20px; width:220px; background-color:#f0f6e4;border: 1px solid #333; margin-bottom: 5px; cursor: pointer} div.ruler div.cursor {height:20px; width:30px; background-color:#3C6E31; color:white; text-align: right; padding-right: 5px; cursor: pointer}
<div class="content_wrap"> <div class="zTreeDemoBackground left"> <input id="citySel" class="formText" type="text" onclick="showMenu(); return false;" readonly value="" style="width:150px;"/> <input id="treeids" type="hidden" name="goods.goodsCategory.id" > <input type="button" onclick="showMenu();" value="∨"> </div> </div> 8<div id="menuContent" class="menuContent" style="display:none; position: absolute;"> <ul id="treeDemo" class="ztree" style="margin-top:0;"></ul> </div>
해당 스크립트는 다음과 같습니다.
<SCRIPT type="text/javascript"> var setting = { view: { dblClickExpand: false }, data: { simpleData: { enable: true } }, callback: { onClick: onClick }, view: { // 不显示对应的图标 showIcon: false } }; function onClick(e, treeId, treeNode) { var zTree = $.fn.zTree.getZTreeObj("treeDemo"), nodes = zTree.getSelectedNodes(), v = ""; ids = ""; nodes.sort(function compare(a,b){return a.id-b.id;}); for (var i=0, l=nodes.length; i<l; i++) { v += nodes[i].name + ","; ids += nodes[i].id + ","; } if (v.length > 0 ) v = v.substring(0, v.length-1); var cityObj = $("#citySel"); cityObj.attr("value", v); // 将选中的id放到隐藏的文本域中 if (ids.length > 0 ) ids = ids.substring(0, ids.length-1); var treeids = $("#treeids"); treeids.attr("value", ids); } function showMenu() { var cityObj = $("#citySel"); var cityOffset = $("#citySel").offset(); $("#menuContent").css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px"}).slideDown("fast"); $("body").bind("mousedown", onBodyDown); } function hideMenu() { $("#menuContent").fadeOut("fast"); $("body").unbind("mousedown", onBodyDown); } function onBodyDown(event) { if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) { hideMenu(); } } var zNodes ; $(document).ready(function(){ // 加载数据 $.ajax({ async : false, cache:false, type: 'POST', dataType : 'json', url: '${base}/admin/goods!getGoodsCategoryTreeJson.action', error: function () { alert('请求失败'); }, success:function(data){ zNodes = data; } }); $.fn.zTree.init($("#treeDemo"), setting, zNodes); }); </SCRIPT>
아래 그림과 같습니다.
<script type="text/javascript"> $(document).ready(function(){ if ("${goods.goodsCategory.id}"!="") { var treeObj = $.fn.zTree.getZTreeObj("treeDemo"); var node = treeObj.getNodeByParam("id", "${goods.goodsCategory.id}" , null); treeObj.selectNode(node,false , false); onClick(event,"${goods.goodsCategory.id}",node,true); } }); </script>

JavaScript 문자열 교체 방법 및 FAQ에 대한 자세한 설명 이 기사는 JavaScript에서 문자열 문자를 대체하는 두 가지 방법 인 내부 JavaScript 코드와 웹 페이지의 내부 HTML을 탐색합니다. JavaScript 코드 내부의 문자열을 교체하십시오 가장 직접적인 방법은 대체 () 메소드를 사용하는 것입니다. str = str.replace ( "find", "replace"); 이 메소드는 첫 번째 일치 만 대체합니다. 모든 경기를 교체하려면 정규 표현식을 사용하고 전역 플래그 g를 추가하십시오. str = str.replace (/fi

이 튜토리얼은 사용자 정의 Google 검색 API를 블로그 또는 웹 사이트에 통합하는 방법을 보여 주며 표준 WordPress 테마 검색 기능보다보다 세련된 검색 경험을 제공합니다. 놀랍게도 쉽습니다! 검색을 Y로 제한 할 수 있습니다

그래서 여기 당신은 Ajax라는이 일에 대해 배울 준비가되어 있습니다. 그러나 정확히 무엇입니까? Ajax라는 용어는 역동적이고 대화식 웹 컨텐츠를 만드는 데 사용되는 느슨한 기술 그룹을 나타냅니다. 원래 Jesse J에 의해 만들어진 Ajax라는 용어

이 기사 시리즈는 2017 년 중반에 최신 정보와 새로운 예제로 다시 작성되었습니다. 이 JSON 예에서는 JSON 형식을 사용하여 파일에 간단한 값을 저장하는 방법을 살펴 봅니다. 키 값 쌍 표기법을 사용하여 모든 종류를 저장할 수 있습니다.

손쉬운 웹 페이지 레이아웃에 대한 jQuery 활용 : 8 에센셜 플러그인 jQuery는 웹 페이지 레이아웃을 크게 단순화합니다. 이 기사는 프로세스를 간소화하는 8 개의 강력한 JQuery 플러그인을 강조합니다. 특히 수동 웹 사이트 생성에 유용합니다.

핵심 포인트 JavaScript에서는 일반적으로 메소드를 "소유"하는 객체를 말하지만 함수가 호출되는 방식에 따라 다릅니다. 현재 객체가 없으면 글로벌 객체를 나타냅니다. 웹 브라우저에서는 창으로 표시됩니다. 함수를 호출 할 때 이것은 전역 객체를 유지하지만 객체 생성자 또는 그 메소드를 호출 할 때는 객체의 인스턴스를 나타냅니다. call (), apply () 및 bind ()와 같은 메소드를 사용 하여이 컨텍스트를 변경할 수 있습니다. 이 방법은 주어진이 값과 매개 변수를 사용하여 함수를 호출합니다. JavaScript는 훌륭한 프로그래밍 언어입니다. 몇 년 전,이 문장은있었습니다

JQuery는 훌륭한 JavaScript 프레임 워크입니다. 그러나 어떤 도서관과 마찬가지로, 때로는 진행 상황을 발견하기 위해 후드 아래로 들어가야합니다. 아마도 버그를 추적하거나 jQuery가 특정 UI를 달성하는 방법에 대해 궁금한 점이 있기 때문일 것입니다.

이 게시물은 Android, BlackBerry 및 iPhone 앱 개발을위한 유용한 치트 시트, 참조 안내서, 빠른 레시피 및 코드 스 니펫을 컴파일합니다. 개발자가 없어서는 안됩니다! 터치 제스처 참조 안내서 (PDF) Desig를위한 귀중한 자원


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

Dreamweaver Mac版
시각적 웹 개발 도구
