基于cookie实现zTree树刷新后展开状态不变

2019/6/27 21:08:08

本文主要是介绍基于cookie实现zTree树刷新后展开状态不变,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

基于cookie实现zTree树刷新后,展开状态不变。

1、除了引用jQuery和zTree的JS外,引用cookie的JS:

<script type="text/javascript" src="~/Scripts/jquery-treeview/lib/jquery.cookie.js"></script>

2、JS代码:

$(function () {
  //ztree设置
  var setting = {
    data: {
      simpleData: {
        enable: true,
        idKey: "id",
        pIdKey: "pId",
        rootPId: null
      }
    },
    callback: {
      onExpand: onExpand,
      onCollapse: onCollapse
    }
  };

  $.ajax({
    type: "POST",
    url: "/Tech/TemplateTypeManage/GetData",
    success: function (data) {
      if (data && data.length != 0) {
        $.fn.zTree.init($("#tree"), setting, data);
        var treeObj = $.fn.zTree.getZTreeObj("tree");
        var cookie = $.cookie("z_tree" + window.location);
        if (cookie) {
          z_tree = JSON2.parse(cookie);
          for (var i = 0; i < z_tree.length; i++) {
            var node = treeObj.getNodeByParam('id', z_tree[i])
            treeObj.expandNode(node, true, false)
          }
        }
      }
    }
  });
});//end $

function onExpand(event, treeId, treeNode) {
  var cookie = $.cookie("z_tree" + window.location);
  var z_tree = new Array();
  if (cookie) {
    z_tree = JSON2.parse(cookie);
  }
  if ($.inArray(treeNode.id, z_tree) < 0) {
    z_tree.push(treeNode.id);
  }
  $.cookie("z_tree" + window.location, JSON2.stringify(z_tree))
}

function onCollapse(event, treeId, treeNode) {
  var cookie = $.cookie("z_tree" + window.location);
  var z_tree = new Array();
  if (cookie) {
    z_tree = JSON2.parse(cookie);
  }
  var index = $.inArray(treeNode.id, z_tree);
  z_tree.splice(index, 1);
  for (var i = 0; i < treeNode.children.length; i++) {
    index = $.inArray(treeNode.children[i].id, z_tree);
    if (index > -1) z_tree.splice(index, 1);
  }
  $.cookie("z_tree" + window.location, JSON2.stringify(z_tree))
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持找一找教程网。



这篇关于基于cookie实现zTree树刷新后展开状态不变的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程