问题
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