Home Web Front-end JS Tutorial Introductory tutorial on using the zTree plug-in drop-down tree_javascript skills

Introductory tutorial on using the zTree plug-in drop-down tree_javascript skills

May 16, 2016 pm 03:05 PM

Recently, because my work requires a tree drop-down box component, after checking the information, there are generally two ways to implement it. One is to use zTree to implement it; the other is to use easyUI to implement it. Because the company's front-end is not designed using easyUI, I chose zTree to implement the drop-down tree.

A simple data format (i.e. simple Json format) is used here, similar to the following Json:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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:"三明"}

     ];

Copy after login

Here we first need an entity bean to encapsulate the corresponding found data, as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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

}

Copy after login

What needs to be noted here is that the second letter in pId is uppercase. If it is written in lowercase, it cannot be constructed into a tree structure, and everything is the root node.

Then, the data retrieved from the database is converted into the beans required by the corresponding ztree, and then converted into the corresponding Json. The code is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

// 获取商品分类树 返回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&#63;"":gcty.getParent().getId());

      treenade.setName(gcty.getName());

      ztreelist.add(treenade);

    }

    return ajax(ztreelist);

  }

Copy after login

Convert the list to the corresponding Json method, as follows:

Json toolkit used:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

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;

  }

Copy after login

In this way, the data required by the front desk is taken out from the library and encapsulated into the corresponding Json.

The next step is to implement the frontend. The js and css that need to be imported by the frontend are as follows:

1

2

3

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

Copy after login

Only demo.css here is added by myself, the others are officially formulated. demo.css is modified from the css used in the official demo, as follows (there are redundant styles here that have not been deleted);

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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}

Copy after login

Then, there is the corresponding drop-down box:

1

2

3

4

5

6

7

8

9

10

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

Copy after login

There is a hidden text box here to store the id corresponding to the content selected in the drop-down box.

The corresponding script is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

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

Copy after login

In this way, a drop-down box is completed.

As shown below:

If you need to write back the corresponding drop-down list data in the modification page, add the following script:

1

2

3

4

5

6

7

8

9

10

11

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

Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone learning the zTree plug-in.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1280
29
C# Tutorial
1257
24
Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

The Role of C/C   in JavaScript Interpreters and Compilers The Role of C/C in JavaScript Interpreters and Compilers Apr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

Python vs. JavaScript: Use Cases and Applications Compared Python vs. JavaScript: Use Cases and Applications Compared Apr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

From Websites to Apps: The Diverse Applications of JavaScript From Websites to Apps: The Diverse Applications of JavaScript Apr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

See all articles