1、新增和修改的时候先将parentNode获取到,定义全局变量
var parentNode = null;
//加入添加资源按钮
function addHoverDom(treeId, treeNode) {
var obj = $('#' + treeNode.tId + '_span');
if ($('#add_' + treeNode.tId).length > 0) {
return;
}
var menu = '<span id="add_'+treeNode.tId+'" class="button add" title="添加子资源"></span>';
obj.after(menu);
var btn = $('#add_' + treeNode.tId);
if (btn)
btn.bind('click', function() {
parentNode = treeNode;
var tId = treeNode.tId;
var parentcode = treeNode.codee;
var code = getLastCode(treeNode);
//alert(treeNode.id);
$('#iframe').attr(
'src',
'${_baseUrl}/add.do?nodeId=' + tId + '&parentcode='
+ parentcode + '&code=' + code);
return false;
});
};
//点击编辑按钮进入编辑
function beforeEditName(treeId, treeNode) {
status = 'edit';
parentNode = treeNode.getParentNode();
$('#iframe')
.attr('src', '${_baseUrl}/edit.do?resId=' + treeNode.id);
return false;
}
当新增或者修改结束的时候,将当前节点的顺序返回:
$("#addForm")
.ajaxSubmit(
{
type: "post",
url: '${_baseUrl}/save.do',
dataType: 'json',
success: function (res) {
window.parent.addChildNode(res,$("#order").val());//在父窗口中添加节点到指定顺序处
window.location.href = '${_baseUrl}/detail.do?resId='
+ res.id;
},
error: function (res) {
}
});
$("#editForm")
.ajaxSubmit(
{
type: "post",
url: '${_baseUrl}/update.do',
dataType: 'json',
success: function (res) {
window.parent.updateNode(res,$("#order").val());//在父窗口中更新顺序
window.location.href = '${_baseUrl}/detail.do?resId='
+ res.id;
},
error: function (res) {
}
});
在ztree新增和修改节点之前先获取当前顺序在父节点的所有子节点中占的顺序:
//获取子节点的最大code
function getIndexOfChildNode(order) {
var childNodes = parentNode.children;
var index = 0;
if (childNodes) {
var lastCode = 0;//childNodes[childNodes.length - 1].codee;
childNodes.forEach(function(n) {
n = parseInt(n.order);
index = n < order ? ++index : index;
});
}
return index;
}
调用ztree自身的添加节点的方法 zTree.addNodes(parentNode, index, node);将节点添加到指定顺序下
//在资源树中添加资源
function addChildNode(node,order) {
var zTree = $.fn.zTree.getZTreeObj('zTree');
var index = getIndexOfChildNode(order);
zTree.addNodes(parentNode, index, node);
}
对于修改的节点信息,可以先删除后添加:
//更新资源树中的资源
function updateNode(res,order) {
var zTree = $.fn.zTree.getZTreeObj('zTree');
var node = zTree.getNodeByParam("id", res.id, null);
zTree.removeNode(node);
var index = getIndexOfChildNode(order);
zTree.addNodes(parentNode, index, res);
}