//build legend key
var svgContainer = d3.select("#TMLegend").append("svg")
.attr("width", 972)
.attr("height", 30);
var width = 35, height = 10, x = 0;
for(var e =0; e < root.children.length; e++){
svgContainer
.append("rect")
.attr("x", 0)
.attr("y", 10)
.attr("width", width)
.attr("height", height)
.attr("transform", "translate("+(36*x++)+",0)")
.style("fill", function(){
return colorArr[root.children[e].name];
})
.attr("title", function(){
return root.children[e].name;
})
.text(function(){
return root.children[e].name;
});
}
d3.selectAll("#TMLegend rect").on("mouseover",function () {
var title = d3.select(this).text();
$("#TMLegendPopUp").show().html("<h4>"+title+"</h4>");
//Popoup position
$(document).mousemove(function(e){
var popLeft = e.pageX + 10;
var popTop = e.pageY + -90;
$("#TMLegendPopUp").css({"left":popLeft,"top":popTop});
$("#TMLegendPopUp h4").css({"background": colorArr[title], "margin":0});
});
});上面的代码是我尝试以id为TMLegend的div为目标,并试图深入到svg:rect.attr(' id '),以获取rect元素id的内容。从那时起,我不再放置ID Attr(),而是现在以text()为目标。当rect节点是硬编码的时候,这段代码可以工作,但是当我使用D3生成它们时就不行了。有没有人有办法用D3动态获取rect元素的文本?
硬编码的html如下所示:
<div id="TMLegend">
<svg width="972" height="30"> 农产品、贵金属、矿产、建材、纺织品,非常感谢。
发布于 2013-06-25 05:27:30
这与预期不谋而合,因为d3.select只选择第一个匹配的元素。您需要使用d3.selectAll来选择图例中的所有矩形,然后在鼠标悬停在每个矩形上时使用d3.select(this)来定位每个矩形。根据我认为您正在尝试实现的目标,您需要以下内容:
d3.selectAll("#TMLegend rect").on("mouseover",function () {
$("#TMLegendPopUp").show()
.html("<h4 style='margin:0'>" + d3.select(this).attr("id") + "</h4>");
//Popoup position
$(document).mousemove(function(e){
var popLeft = e.pageX + 10;
var popTop = e.pageY + -90;
$("#TMLegendPopUp").css({"left":popLeft,"top":popTop});
});
});https://stackoverflow.com/questions/17284180
复制相似问题