D3:如何在点击事件中删除形状? [英] D3: How delete shape on click event?

查看:93
本文介绍了D3:如何在点击事件中删除形状?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I currently have a world map that on the click event on one of the countries in my map will add a rectangle on the same place with a different color. The problem with the code I have is that clicking the countries will result in rectangles being added in the svg(on every click a rectangle is added on top of the other) because I am appending them. What I'd like to do is delete the previous added rectangle when one of the countries is clicked and then adding the next one.

我当时正在考虑使用.remove(),但是我不确定这是否正确,并且不确定如何在代码中实现它.

I was thinking about using .remove() but I'm not sure if that is the right way and I'm not sure how to implement it in the code.

任何帮助或建议,我们将不胜感激! 预先感谢!

Any help or suggestion are greatly appreciated! Thanks in advance!

我拥有的代码

.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)");

        }
    }

推荐答案

您可以做类似的事情

        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();

   }

这篇关于D3:如何在点击事件中删除形状?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆