在灰色节点之间添加链接 - 定向图编辑器d3.js

时间:2015-04-27 17:06:18

标签: javascript svg d3.js

我已经使用了"定向图编辑器" - http://bl.ocks.org/rkirsling/5001347用于我的研究项目,我已对其进行了更新,现在看起来像这样 - http://jsfiddle.net/fb89orLt/2/

我的问题是关于通过链接将2个灰色节点链接在一起。现在,我正在存储节点' &安培;链接'以下数组中的信息:

var words1 = ['Habitat for Humanity', 'Caring', 'Helping', 'People', 'Safety', 'Security', 'Shelter', 'Community', 'Volunteering'];
var sources1 = ['Helping', 'Community', 'Caring', 'Safety', 'Security'];
var targets1 = ['Community', 'Volunteering', 'People', 'Security', 'Shelter'];


var words2 = ['Starbucks', 'Coffee', 'Tea', 'Chai', 'Milk Tea', 'Mocha', 'Drink', 'Smoothy', 'Milk', 'Cappuccino'];
var sources2 = ['Coffee', 'Smoothy', 'Drink', 'Milk Tea', 'Tea'];
var targets2 = ['Milk', 'Drink', 'Mocha', 'Chai', 'Coffee'];

我通过了数组" words1" &安培; " words2"在"节点"宾语。我遇到了将sources1,targets1,sources2,targets2数组元素传递给source& amp的问题。 "链接"的目标宾语。我试图找到nodes1中的elements1,targets1数组中的元素索引,以便我可以将它们推送到链接对象中,但是没有成功。现在,我用这种方式硬编码:

links.push({"source": nodes[2], "target": nodes[7], "left": false, "right": false, "colour": "#000", "length": 250});
links.push({"source": nodes[1], "target": nodes[3], "left": false, "right": false, "colour": "#000", "length": 250});
links.push({"source": nodes[7], "target": nodes[8], "left": false, "right": false, "colour": "#000", "length": 250});
links.push({"source": nodes[4], "target": nodes[5], "left": false, "right": false, "colour": "#000", "length": 250});
links.push({"source": nodes[5], "target": nodes[6], "left": false, "right": false, "colour": "#000", "length": 250});


links.push({"source": nodes[10], "target": nodes[17], "left": false, "right": false, "colour": "#000", "length": 250});
links.push({"source": nodes[15], "target": nodes[16], "left": false, "right": false, "colour": "#000", "length": 250});
links.push({"source": nodes[14], "target": nodes[15], "left": false, "right": false, "colour": "#000", "length": 250});
links.push({"source": nodes[12], "target": nodes[13], "left": false, "right": false, "colour": "#000", "length": 250});
links.push({"source": nodes[10], "target": nodes[11], "left": false, "right": false, "colour": "#000", "length": 250});

我想知道是否有更好,更有效,更简单的方法使用数组和/或对象来做到这一点?

1 个答案:

答案 0 :(得分:0)

使用函数创建链接:

function createLink(src, tgt){
  var s=nodes.indexOf(src), t=nodes.indexOf(tgt)
  if(s==-1) {alert('unknown source ' + src)}
  if(t==-1) {alert('unknown target ' + tgt)}
  links.push({"source": src, "target": tgt, "left": false, "right": false, "colour": "#000", "length": 250});
}

for(var i=0;i<sources1.length;i++)createLink(sources1[i], targets1[i]);
for(var i=0;i<sources2.length;i++)createLink(sources2[i], targets2[i]);

如果indexOf未定义,请使用https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

中的polyfill
相关问题