我目前有一张世界地图,在我的地图上某个国家/地区的click事件上,它将在同一地方添加具有不同颜色的矩形。我的代码存在的问题是,单击国家(地区)将导致在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)");
}
}
你可以做类似的事情
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();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句