<body>
<script src="d3.js" charset="utf-8"></script>
<button type="button" id="changeButton" onClick="hide(this)">Hide</button><br>
<object data="MineralPorn.svg" id="myGraph">graph</object>
<script>
function getGraph() {
return d3.select(document.getElementById("myGraph").contentDocument);
}
function nodeOnClick(d, i) {
console.log(d.attr("class"));
}
function setup() {
getGraph().select("#nodes")
.selectAll("circle")
.on("click", function(d, i) {nodeOnClick(d, i);} );
console.log(getGraph().selectAll("#nodes").selectAll("circle"));
}
state="visible";
function hide(button) {
setup();
var textElements = getGraph().selectAll("text");
if (state=="visible") { value="none"; state="invisible"; }
else { value=""; state="visible"; }
button.firstChild.data = state=="visible" ? "Hide" : "Unhide";
textElements.style("display",value);
}
</script>
</body>
svg文件为here。 svg的基本结构是:
<svg>
<g id="edges"></g>
....
<g id="nodes">
<circle class="thing1"/>
<circle class="thing2"/>
....
</g>
</svg>
预期行为:单击“隐藏”按钮后,节点上写入的文本将消失,函数nodeOnClick将链接到SVG中的每个圆圈。单击任何圆圈后,其类将打印到控制台。
观察到的行为:不是打印类,而是将Javascript错误TypeError: d is undefined
打印到控制台。
文档让我相信d和i作为参数传递给回调函数,但似乎它们不是......?我如何正确地将onClick功能链接到SVG圈子?我的假设“d”是d3.selection正确吗?