【问题标题】:D3: How delete shape on click event?D3:如何在点击事件中删除形状?
【发布时间】:2014-06-23 04:36:40
【问题描述】:

我目前有一张世界地图,在我的地图中某个国家的点击事件中,它会在同一个地方添加一个不同颜色的矩形。我拥有的代码的问题是,单击国家/地区将导致在 svg 中添加矩形(每次单击时都会在另一个顶部添加一个矩形),因为我正在附加它们。我想做的是在单击其中一个国家/地区时删除先前添加的矩形,然后添加下一个。

我正在考虑使用 .remove() 但我不确定这是否是正确的方法,我不确定如何在代码中实现它。

非常感谢任何帮助或建议! 提前致谢!

我的代码

.on("click",clicked)



function clicked(d,i) {
        if(d.properties.name === "Mexico") {
            var rectGroup = svg.append("g");

            var rectGreen = rectGroup.append("rect")
                  .attr("width", 100)
                          .attr("height", 100)
                          .attr("fill", "green")
                          .attr("transform", "translate(50, 0)");

        }else {
            var rectGroup = svg.append("g");

            var rectBlue = rectGroup.append("rect")
                  .attr("width", 100)
                          .attr("height", 100)
                          .attr("fill", "blue")
                          .attr("transform", "translate(50, 0)");

        }
    }

【问题讨论】:

    标签: d3.js onclick


    【解决方案1】:

    你可以做类似的事情

            var creation=Date.now();
            var rectBlue = rectGroup.append("rect")
                   .attr("width", 100)
                   .attr("height", 100)
                   .attr("fill", "blue")
                   .attr("transform", "translate(50, 0)")
                   .attr('id','rect_'+creation)
                   .attr('onclick',"removeRect('rect_"+creation+"')")
    

    ;

    然后有一个函数

        function removeRect(id){
              d3.selectAll('g #'+id).remove();
    
       }
    

    【讨论】:

      猜你喜欢
      • 2014-04-19
      • 2019-12-30
      • 1970-01-01
      • 2017-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多