你能否告诉我如何点击绘制的元素来存储索引并获取它?在我的情况下,当收到一个事件时,会绘制一个字形。我只想为每个字形分配一个no或index [0,1,2,...]。稍后点击一个字形时,我只想检索分配给否的字符。这里创建一个小例子,数据集在我的情况下并不完全相同。感谢。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title> Icon </title>
<script type="text/javascript" src="lib/d3/d3.v3.js"></script>
</head>
<body>
<p id="drawing">
<script>
// data is not same as here, just to explain the requirement created it.
var incomingData = [40, 50, 80, 72];
var svg = d3.select("#drawing")
.append("svg")
.attr("height", 200)
.attr("width", 200)
.attr("transform", "translate(20, 20)");
for(var i = 0; i < incomingData.length; ++i) {
svg.append("circle")
.attr("cx", 10 + incomingData[i])
.attr("cy", 10)
.attr("r", 5)
.style("fill", "grey")
.on("mouseover", function () {
d3.select(this)
.style("fill", "orange");
})
.on("mouseout", function () {
d3.select(this)
.style("fill", "gray");
})
.on("click", function() {
alert("Index= .");
});
}
</script>
</body>
</html>
答案 0 :(得分:1)
是否有特殊原因导致您未以d3
方式绑定数据?我会建议像:
svg.selectAll('circle').data(incomingData).enter().append("circle")
.attr("cx", function(d) {
return 10 + d;
})
.attr("cy", 10)
.attr("r", 5)
.style("fill", "grey")
.on("mouseover", function() {
d3.select(this)
.style("fill", "orange");
})
.on("mouseout", function() {
d3.select(this)
.style("fill", "gray");
})
.on("click", function(d, i) {
alert("Index= " + i);
});
这样,您可以使用incomingData
绑定data
,因此每个元素都有一个index
,例如,在这里:http://alignedleft.com/tutorials/d3/binding-data