我试图在使用D3.js映射数据的程序中利用Opentip.js中的功能集。
我无法弄清楚如何将新的Opentip对象绑定到构成地图的未命名元素。
这是一段代码摘录,说明了我采取的方法:
<script type="text/javascript">
var dataset = [[4,2,'Bob'], [5,7,'Sally'], [2,2,'Marvin']];
var width = 38;
var height = 38;
var margin = 20;
function giveX(d) { return d[0] * width + margin }
function giveY(d) { return d[1] * height + margin }
var mapdiv = d3.select("#map")
.append("svg")
.attr("height", 680)
.attr("width", 980)
.style('border', '1px solid black')
var pips = mapdiv.selectAll("circle")
.data(dataset)
.enter().append("circle")
.style("fill", "red")
.style("stroke", "black")
.attr("cx", function(d) {return giveX(d)})
.attr("cy", function(d) {return giveY(d)})
.attr("r", width/2)
</script>
Opentip对象的构造函数只需要我提供元素标识符,但我不清楚如何引用动态创建的&#34; circle&#34;元件。
我已经尝试将代码附加到selectAll()调用中,但这并没有成功。
答案 0 :(得分:2)
以下是使用data-ot
属性的简短示例:
<!DOCTYPE html>
<html>
<head>
<script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/opentip/2.4.6/downloads/opentip-native.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/opentip/2.4.6/css/opentip.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script>
var svg = d3.select('body')
.append('svg')
.attr('width', 200)
.attr('height', 200);
svg.selectAll('circle')
.data(d3.range(10))
.enter()
.append('circle')
.attr('cx', function(d) { return Math.random() * 200 } )
.attr('cy', function(d) { return Math.random() * 200 } )
.attr('r', 10)
.style('fill', 'steelblue')
.attr("data-ot", function(d,i){
return "Circle " + i;
});
</script>
</body>
</html>
以下是使用构造函数的示例:
<!DOCTYPE html>
<html>
<head>
<script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/opentip/2.4.6/downloads/opentip-native.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/opentip/2.4.6/css/opentip.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script>
var svg = d3.select('body')
.append('svg')
.attr('width', 200)
.attr('height', 200);
svg.selectAll('circle')
.data(d3.range(10))
.enter()
.append('circle')
.attr('cx', function(d) { return Math.random() * 200 } )
.attr('cy', function(d) { return Math.random() * 200 } )
.attr('r', 10)
.style('fill', 'steelblue')
.each(function(d,i){
new Opentip(this).setContent("Circle " + i);
})
</script>
</body>
</html>