我正在对SQL数据库进行直观表示,并使用Francois Zaninotto的CodeFlower(由D3.js提供支持)来完成它。
我的问题是,如何访问被点击节点的父节点的名称变量? 我意识到这个问题与How to get data of parent node in d3.js类似,但他们的回答似乎不清楚我的目的。我也是D3的新手,所以这可能是原因。
我的json代码格式:
{"name":"CRS_LOG_LEVEL","children":[{"name":"CRS_LOG","children":[{"name":"LOG_DESC","size":7,"type":"column"},{"name":"LOG_ID","size":7,"type":"column"},{"name":"LOG_TMSTMP","size":7,"type":"column"},{"name":"LOG_LEVEL_NBR","size":7,"type":"column"},{"name":"LOG_EVENT_CD","size":7,"type":"column"}],"size":100,"type":"table"}],"size":100,"type":"root"}
我的鼠标点击事件监听器:
CodeFlower.prototype.click = function(d) {
// Toggle children on click.
if (d.children) { //This makes the node that has children collapse and grow in size.
d._children = d.children;
d.children = null;
} else {
var schemaName;
var tableName;
var columnName;
if(d.type==="column") //only check the parent information if type===column
{
columnName = d.name;
//tableName = Parent's name
//schemaName = Parent's Parent's name
}
d.children = d._children;
d._children = null;
}
this.update();
};
^上面的代码是我在这个问题顶部引用的GitHub项目上的Francois'CodeFlower.js的略微修改版本。
答案 0 :(得分:1)
如果您更改CodeFlower.prototype.flatten
以向每个节点添加父引用,则稍后在click事件中遍历树将变得很简单。这在结构上类似于D3在tree.nodes中的作用,但没有定位逻辑。
答案 1 :(得分:0)
以下代码应该可以胜任。
var JSON = {"name":"CRS_LOG_LEVEL","children":[{"name":"CRS_LOG","children":[{"name":"LOG_DESC","size":7,"type":"column"},{"name":"LOG_ID","size":7,"type":"column"},{"name":"LOG_TMSTMP","size":7,"type":"column"},{"name":"LOG_LEVEL_NBR","size":7,"type":"column"},{"name":"LOG_EVENT_CD","size":7,"type":"column"}],"size":100,"type":"table"}],"size":100,"type":"root"}
for (var i = 0; i<JSON.children.length; i++) {
for (var j = 0; j<JSON.children[i].children.length; j++) {
var parentIndex = JSON.children[i].children.indexOf(d);
if (parentIndex !== -1) {
var parentName = JSON.children[i].children[parentIndex].name;
}
}
}
变量parentName
应包含您要查找的名称。
请注意,您不应在脚本中包含第一行代码(var JSON
...),并且应该用数据对象替换JSON(在我的脚本中)的每个外观。