<<博客迁移,原文来自我的51cto博客http://11095961.blog.51cto.com/11085961/1954277>>
自上一篇说明的点击节点更换节点图标后,发现网上有许多关于点击节点加载数据(或点击收缩节点)的问题,一直没看到满意的解答。现在在上一篇的基础上做出如下实现:点击节点动态加载/收缩子节点。
先说关键点,还是注册在事件的处理函数:
var mockData1 = {"name":"小米11","symbol":"circle","cusField":"product","itemStyle":{"normal":{"label":{"show":true,"position":"right"}}}};
var mockData2 = {"name":"小米22","symbol":"circle","cusField":"product","itemStyle":{"normal":{"label":{"show":true,"position":"right"}}}};
//简单使用1,点击加载一个节点
function clickFun(param) {
console.log(JSON.stringify(param));
if(param.data.children)
param.data.children.push(mockData1);
else
param.data.children = [deepCopy(mockData1),deepCopy(mockData2)];
// console.log(param);
chart.refresh(); //一定要refresh,否则不起作用
}
//关键点!
//显示的图片是否有子节点以及是否收缩了建议用不同的symbol图片(不直接使用的图片预加载过来)
function clickFun2(param) {
// console.log(JSON.stringify(param));
if(!(param.data.children && param.data.children.length > 0)) {
console.log('open');
if(param.data.children_bak) {
param.data.children = param.data.children_bak;
}
else {
param.data.children = [deepCopy(mockData1),deepCopy(mockData2)]; //加载数据,此处用测试数据
}
} else {
console.log('close');
param.data.children_bak = param.data.children;
param.data.children = []; //root节点会在refresh时读children的length
}
console.log(param);
chart.refresh(); //一定要refresh,否则不起作用
}
function deepCopy(p, c) {
var c = c || {};
for (var i in p) {
if (typeof p[i] === 'object') {
c[i] = (p[i].constructor === Array) ? [] : {};
deepCopy(p[i], c[i]);
} else {
c[i] = p[i];
}
}
return c;
}
效果图:
完整源码:https://github.com/hzhqk/echarts.git 下 dynamic echarts tree/load sub-nodes dynamicly目录下