javascript 如何将点击事件分配给 d3js 中的每个 svg 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25123003/
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-28 03:59:10  来源:igfitidea点击:

How to assign click event to every svg element in d3js

javascriptsvgd3.js

提问by vjdhama

I have added nine rectangles in a svg element. How do i add click event to each one?

我在 svg 元素中添加了九个矩形。我如何为每个添加点击事件?

var nodeValues = [0, 1, 2, 3, 4, 5, 6, 7, 8];

var colors = ["aqua", "darkblue", "black", "red", "green", "gray", "navy", "orange", "teal"];

var main = d3.select("#main");

var svg = main.append("svg")
    .data(nodeValues)
    .attr("width", 300)
    .attr("height", 300);

var elementAttr = function (index) {
    return {
        x: (index % 3) * 100,
        y: Math.floor((index / 3)) * 100,
        width: 95,
        height: 95
    }
}

for (var index in nodeValues) {
    var rect = svg.append("rect")
        .attr(elementAttr(index))
        .style("fill", "red" );
}

Here is the Jsfiddle.

这是Jsfiddle

UPDATE: I wish to change attributes like width of rectangle on a click event.

更新:我希望在单击事件上更改矩形宽度等属性。

回答by Stephen Thomas

for (var index in nodeValues) {
    var rect = svg.append("rect")
        .attr(elementAttr(index))
        .style("fill", "red" )
        .on('click', function(d,i) {
            // handle events here
            // d - datum
            // i - identifier or index
            // this - the `<rect>` that was clicked
        });
}

回答by Max Alcala

I gave a vote to Stephen's answer but it's actually just missing one part - instead of .click, it's

我对斯蒂芬的回答投了票,但实际上只是缺少一个部分 - 而不是 .click,而是

.on("click", function(d){...

Here's some documentation. Also, I've Hymaned Mike's example of zooming with circlesin order to implement the binder listener. Here's a fiddlethat shows it.

这是一些文档。此外,为了实现活页夹侦听器,我还使用了 Mike 的用圆圈进行缩放的示例。这是一个显示它的小提琴

Hope that helps!

希望有帮助!

回答by Lars Kotthoff

I've refactored your code to be more D3-like -- in particular, you don't need a loop if you use D3's selections and data matching. The code then looks like this:

我已经将您的代码重构为更像 D3 —— 特别是,如果您使用 D3 的选择和数据匹配,则不需要循环。代码如下所示:

svg.selectAll("rect")
    .data(nodeValues).enter().append("rect")
    .each(function(d) {
        var attrs = elementAttr(d);
        d3.select(this).attr(attrs);
    })
    .style("fill", rectColor);

Adding the click handler is just an additional statement at the end of this:

添加点击处理程序只是最后的附加声明:

    .on("click", function() {
        d3.select(this).attr("width", 120);
    });

Complete demo here.

在这里完成演示。