【问题标题】:How to assign click event to every svg element in d3js如何将点击事件分配给d3js中的每个svg元素
【发布时间】:2014-08-19 15:47:49
【问题描述】:

我在一个 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" );
}

这里是Jsfiddle

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

【问题讨论】:

    标签: javascript svg d3.js


    【解决方案1】:
    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
            });
    }
    

    【讨论】:

    • 我尝试使用.click,但我似乎没有工作。你能发布有效的 jsfiddle 链接吗?
    • 我尝试在匿名函数中将&lt;rect&gt; 的属性更改为this.attr("width", 100)。它没有用。
    • 你可能想使用d3.select(this).attr("width", 100)而不是this.attr("width", 100) 另外,如果你想稍微改进你的代码,你应该使用进入-更新-退出模式,查看jsfiddle.net/z7Y9X/11
    • 伟大的@VinhTran 有效!从现在开始,我肯定会使用进入-更新-退出模式。
    • 感谢@stephen-thomas 记录回调 - 评论“this - the &lt;rect&gt; that was clicked”比“使用由来自文档的调用者。 :)
    【解决方案2】:

    我已将您的代码重构为更像 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);
    

    添加点击处理程序只是在此末尾的附加语句:

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

    完整的演示here

    【讨论】:

      【解决方案3】:

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

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

      这里有一些documentation。此外,为了实现活页夹侦听器,我还使用了 Mike 的 zooming with circles 示例。这是一个显示它的fiddle

      希望有帮助!

      【讨论】:

        猜你喜欢
        • 2012-08-29
        • 2017-05-18
        • 2013-09-29
        • 1970-01-01
        • 2023-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-09
        相关资源
        最近更新 更多