单击时,在 d3.js 中单独显示其他数据 div;按价值传递
On click, display other data in separate div in d3.js; Passing by value
我正在研究 d3 中的无向图。当我点击一个节点时,我想在 svg 之外的一个单独的 div (class: info) 中显示它的数据。但是,我无法弄清楚如何将数据从节点放置到 div.
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 5)
.style("fill", function(d) { return color(d.group); })
.call(force.drag)
.on("click", function(d){
d3.selectAll(".node").attr('r', 5)
.style("fill", function(d) { return color(d.group); })
.style("stroke","none");
d3.select(this).attr('r', 25)
.style("fill","lightcoral")
.style("stroke","red");
d3.select("#info").text(/* TEXT */);
});
我试过了:
- 我试过了
d3.select("#info").text(function(d){return d.text;});
。但是,如果我没有理解错的话,d
将引用当前选择的数据。因此,有了这个,d3.select("#info")
中没有数据,因为当前选择是 div #info
.
- 我还尝试将
function(d){return d.text;}
绑定到一个变量,然后将该变量传递给 text()
。但是,Javascript 不按值传递;这与#1 的场景相同。
我读过有关为文本创建对象的信息。我想我在这里忽略了一些东西。有没有一种优雅的方法可以将数据从节点显示到 svg 外部的 div?
拉斯是对的:d3.select("#info").text(d.text);
您所做的,d3.select("#info").text(function(d){return d.text;});
,通过将一个函数传递给 .text() 是为了让该函数在您刚刚选择的 #info 元素的上下文中求值。但是您已经处于要从中获取文本的节点的上下文中,并且您正在访问的 d
(在 Lars 的回答中)是 d
传递给您的点击回调。所以,只要 d
有你想要的 .text 属性,你就应该做生意。
我正在研究 d3 中的无向图。当我点击一个节点时,我想在 svg 之外的一个单独的 div (class: info) 中显示它的数据。但是,我无法弄清楚如何将数据从节点放置到 div.
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 5)
.style("fill", function(d) { return color(d.group); })
.call(force.drag)
.on("click", function(d){
d3.selectAll(".node").attr('r', 5)
.style("fill", function(d) { return color(d.group); })
.style("stroke","none");
d3.select(this).attr('r', 25)
.style("fill","lightcoral")
.style("stroke","red");
d3.select("#info").text(/* TEXT */);
});
我试过了:
- 我试过了
d3.select("#info").text(function(d){return d.text;});
。但是,如果我没有理解错的话,d
将引用当前选择的数据。因此,有了这个,d3.select("#info")
中没有数据,因为当前选择是 div#info
. - 我还尝试将
function(d){return d.text;}
绑定到一个变量,然后将该变量传递给text()
。但是,Javascript 不按值传递;这与#1 的场景相同。
我读过有关为文本创建对象的信息。我想我在这里忽略了一些东西。有没有一种优雅的方法可以将数据从节点显示到 svg 外部的 div?
拉斯是对的:d3.select("#info").text(d.text);
您所做的,d3.select("#info").text(function(d){return d.text;});
,通过将一个函数传递给 .text() 是为了让该函数在您刚刚选择的 #info 元素的上下文中求值。但是您已经处于要从中获取文本的节点的上下文中,并且您正在访问的 d
(在 Lars 的回答中)是 d
传递给您的点击回调。所以,只要 d
有你想要的 .text 属性,你就应该做生意。