【发布时间】:2016-01-07 15:50:05
【问题描述】:
我有一个网页,其中包含 11 个不同区域中的每一个的 4 个 d3 图表。其中一个图表是面积图,代码 sn-p 是:
for (mm=0; mm<regions.length; mm++) {
areas.append("path")
.attr("class",function(d,i){ return "area cons ar"+i+" region"+mm;} )
.attr("id", function(d,i) { return "area_"+i+"_"+mm})
.attr("d", function(d,i) { return area(d)} );
var test = d3.selectAll("path.region"+mm)
.call(d3.helper.tooltip()
.attr("class", function(d, i) { return "tooltip"; })
.text(function(d, i){
console.log(mm);
return "i "+consSubProducts[i]+', i: '+i;}));
}
我想在图表中添加工具提示。在面积图中,每个地区都有不同的产品。有些有 7 个产品,有些有 5 个。我需要在其运行时值 (0-10) 处使用 mm 变量来调用 consSubProducts 当前所在的正确产品数组。 (ConsSubProducts 在 for...循环的顶部设置为不同的产品数组,但与 mm 一样,代码只能看到 finally 设置的数组,而不是运行时数组。)
在此代码中,mm 始终返回 11,即它返回 mm 的最终值,而不是运行时的值。
我尝试在 tooltip() 和 .text(function(d,i,mm) 中传递 mm - 后者显然不起作用,因为它期待 j。我也尝试将 mm 附加到类或对象的 ID,但在 call() console.log(this) 记录 object.window。
我尝试过修改 tooltip.js,但虽然我可以生成我想要的标签,但我不知道如何覆盖文本。 Tooltip.js:
d3.helper = {};
d3.helper.tooltip = function(){
var tooltipDiv;
var bodyNode = d3.select('body').node();
var attrs = {};
var text = '';
var styles = {};
function tooltip(selection){
selection.on('mouseover.tooltip', function(pD, pI){
var name, value;
// Clean up lost tooltips
d3.select('body').selectAll('div.tooltip').remove();
// Append tooltip
tooltipDiv = d3.select('body').append('div');
tooltipDiv.attr(attrs);
tooltipDiv.style(styles);
var absoluteMousePos = d3.mouse(bodyNode);
tooltipDiv.style({
left: (absoluteMousePos[0] + 10)+'px',
top: (absoluteMousePos[1] - 15)+'px',
position: 'absolute',
'z-index': 1001
});
// Add text using the accessor function, Crop text arbitrarily
tooltipDiv.style('width', function(d, i){ return (text(pD, pI).length > 80) ? '300px' : null; })
.html(function(d, i){return text(pD, pI);});
})
.on('mousemove.tooltip', function(pD, pI){
// Move tooltip
var absoluteMousePos = d3.mouse(bodyNode);
tooltipDiv.style({
left: (absoluteMousePos[0] + 10)+'px',
top: (absoluteMousePos[1] - 15)+'px'
});
// Keep updating the text, it could change according to position
tooltipDiv.html(function(d, i){ return text(pD, pI); });
})
.on('mouseout.tooltip', function(pD, pI){
// Remove tooltip
tooltipDiv.remove();
});
}
tooltip.attr = function(_x){
if (!arguments.length) return attrs;
attrs = _x;
return this;
};
tooltip.style = function(_x){
if (!arguments.length) return styles;
styles = _x;
return this;
};
tooltip.text = function(_x){
if (!arguments.length) return text;
text = d3.functor(_x);
return this;
};
return tooltip;
};
任何帮助表示赞赏!
【问题讨论】:
标签: javascript arrays d3.js tooltip