javascript d3.js 将单击动作添加到强制布局圆圈?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9080862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 05:32:13  来源:igfitidea点击:

d3.js adding click action to a force layout circle?

javascriptsvgd3.jsforce-layout

提问by erogol

I am working on to create a undirected graph with force layout. In addition, I try to chage each circle's (node's) color with click event. Is there any idea to add such event on the circle elements. I tyry this code however it is not working.

我正在努力创建一个带有力布局的无向图。此外,我尝试通过单击事件更改每个圆圈(节点)的颜色。有什么想法可以在圆圈元素上添加这样的事件。我很喜欢这段代码,但它不起作用。

vis.selectAll("circle.node").on("click", function(d){
    vis.select(d).attr(r, 25)
    .style("fill","lightcoral")
    .style("stroke","red");
});

回答by methodofaction

select(d)references the data, not the element. You need to select(this)

select(d)引用数据,而不是元素。你需要select(this)

 vis.selectAll("circle.node").on("click", function(){
            d3.select(this).attr('r', 25)
                .style("fill","lightcoral")
                .style("stroke","red");
        });

回答by Lars Kotthoff

vis.select(this)gives me a DOM exception. d3.select(this)works for me. You can also use d3.event.targetto access the DOM element that is clicked on.

vis.select(this)给了我一个 DOM 异常。d3.select(this)对我来说有效。您还可以使用d3.event.target访问被单击的 DOM 元素。