D3: How delete shape on click event?

a 夏天 提交于 2019-12-11 07:06:19

问题


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.

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!

the code I have

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

        }
    }

回答1:


you can do something like

        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+"')")

;

and then have a function

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

   }


来源:https://stackoverflow.com/questions/24355451/d3-how-delete-shape-on-click-event

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!