【发布时间】:2012-04-20 20:07:10
【问题描述】:
我是 JavaScript 新手。我正在使用 D3 构建一些图表。我想显示鼠标在 SVG 元素上的点击次数。
目前我可以显示椭圆并可以跟踪椭圆的点击次数。我想覆盖椭圆上不断变化的鼠标点击次数。
我让它工作,以便显示初始变量,但无法解决如何显示变量更改(即额外的鼠标点击)。我想要它,以便在单击椭圆后立即更新文本。
我的代码如下。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
</head>
<body>
<div id="viz"></div>
<script type="text/javascript">
var clicks = 0;
var sampleSVG = d3.select("#viz")
.append("svg:svg")
.attr("width", 400)
.attr("height", 800);
sampleSVG.append("svg:ellipse")
.style("stroke", "gray")
.style("fill", "white")
.attr("rx", 20)
.attr("ry", 25)
.attr("cx", 50)
.attr("cy", 50)
.on("mouseover", function(){d3.select(this).style("fill", "aliceblue");})
.on("mouseout", function(){d3.select(this).style("fill", "white");})
.on("click", function(){clicks = clicks+1
})
sampleSVG.append("svg:text")
.text(clicks)
.attr("x", 50)
.attr("y", 50)
.attr("fill", "black");
</script>
</body>
</html>
我尝试添加到 sampleSVG.text(点击) 到我的 onclick 功能,但它没有用。
同样作为一个更普遍的问题,我的文本(var clicks)是否应该附加到 sampleSVG 还是应该创建一个新变量 sampleText 并将其覆盖在 sampleSVG 上?
感谢您的帮助
R
【问题讨论】:
标签: javascript d3.js