ztree 实现树同级拖动、节点删除、保存结构

洛阳醉长安行

ztree.js 如何实现树结构顺序的实时存储,经过和后端一番的讨论后,最终定下了在触发拖动的时候调用接口存储同级下的节点顺序,并且只能同级拖动:

  function beforeDrop(treeId, treeNodes, targetNode, moveType) {
    var moveNode = treeNodes[0];
    switch (moveType) {
      case "prev":
      case "next":
        if (moveNode.parentId == targetNode.parentId) {
          //只能同级拖动
          return true;
        }
        break;
      // case "inner":
      //     if (moveNode.parentId == targetNode.parentId) {
      //       return true;
      //     }
      //     break;
    }
    return false;
  }
    function singleCick(event, tree, treeNode) {
    var nodes = treeObj.getSelectedNodes();
    //设置父节点不能被选择
    if (tree.children) {
      return false;
    }
    if (nodes.length > 0) {
      treeNodeData = nodes[0];
    }
  }
    //保存节点的排序顺序
  function saveNodesSort(currNode) {
    var currLevelNodes = currNode.getParentNode().children; //获取同级的所有节点
    var currLevelNodesIds =
      currLevelNodes &&
      currLevelNodes.map(function (item, idx) {
        return item.id;
      });
    $.ajax({
      url: "/savesort.api",
      method: "get",
      data: {
        ids: currLevelNodesIds.join(),
      },
      success: function (res) {
        if (res.code == 0) {
          console.log("排序保存成功");
        }
      },
      error: function (res) {
        layer.msg(res.desc);
      },
    });
  }
  
  var setting = {
    callback: {
      onClick: zTreeOnClick,
      beforeClick: singleCick,
      beforeDrop: beforeDrop,
      onDrop: function (
        event,
        treeId,
        treeNodes,
        targetNode,
        moveType,
        isCopy
      ) {
        //拖动完成保存顺序
        saveNodesSort(treeNodes[0]);
      },
      beforeRemove: function (treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj(treeId);
        layer.confirm(
          "是否删除" + treeNode.name+",删除后无法恢复",
          {
            btn: ["确定", "取消"],
          },
          function (index) {
            zTree.removeNode(treeNode);
            layer.close(index);
            deleteNode(treeNode.id);
          }
        );
        return false;
      },
    },
    view: {
      selectedMulti: false,
    },

    edit: {
      enable: true,
      showRemoveBtn: function (treeId, treeNode) { //父节点不显示删除按钮
        return !treeNode.isParent;
      },
      showRenameBtn: false,
      drag: {
        prev: true,
        next: true,
        inner: false,
        isCopy: false,
        isMove: true,
      },
    },
  };
  
  var ztreeObj = $.fn.zTree.init($("#treeDemo"), setting, [treeData]);
阅读 1.2k

charging...

27 声望
2 粉丝
0 条评论

charging...

27 声望
2 粉丝
文章目录
宣传栏