Javascript 如何将d,i参数传递给on(";click";)函数? 隐藏 图表 函数getGraph(){ 返回d3.select(document.getElementById(“myGraph”).contentDocument); } 功能节点单击(d,i){ console.log(d.attr(“类”); } 函数设置(){ getGraph().选择(“节点”) .selectAll(“圆圈”) .on(“click”,函数(d,i){nodeOnClick(d,i);}); log(getGraph().selectAll(#nodes”).selectAll(“圆圈”); } state=“可见”; 功能隐藏(按钮){ 设置(); var textElements=getGraph()。选择全部(“文本”); 如果(state==“visible”){value=“none”;state=“visible”} else{value=”“;state=“可见”} button.firstChild.data=状态==“可见”?“隐藏”:“取消隐藏”; textElements.style(“显示”,值); }
svg文件是。svg的基本结构是:Javascript 如何将d,i参数传递给on(";click";)函数? 隐藏 图表 函数getGraph(){ 返回d3.select(document.getElementById(“myGraph”).contentDocument); } 功能节点单击(d,i){ console.log(d.attr(“类”); } 函数设置(){ getGraph().选择(“节点”) .selectAll(“圆圈”) .on(“click”,函数(d,i){nodeOnClick(d,i);}); log(getGraph().selectAll(#nodes”).selectAll(“圆圈”); } state=“可见”; 功能隐藏(按钮){ 设置(); var textElements=getGraph()。选择全部(“文本”); 如果(state==“visible”){value=“none”;state=“visible”} else{value=”“;state=“可见”} button.firstChild.data=状态==“可见”?“隐藏”:“取消隐藏”; textElements.style(“显示”,值); },javascript,d3.js,Javascript,D3.js,svg文件是。svg的基本结构是: <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">gr
<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>
....
....
预期行为:单击“隐藏”按钮后,节点上写入的文本消失,函数nodeOnClick链接到SVG中的每个圆。单击任意圆后,其类将打印到控制台
观察到的行为:不是打印类,而是将Javascript错误TypeError:d未定义打印到控制台
文档让我相信d和i是作为参数传递给回调函数的,但它们似乎不是。。。?如何正确地将onClick函数链接到SVG圆?我假设“d”是d3.selection是否正确?您的d3.js是否与html文件位于同一目录中?在节点单击,将d
更改为d3。选择(此)
“我假设“d”是d3.selection是否正确?”不,不是,d
在该上下文中是一个数据对象,它已使用先前的d3代码链接到元素。您从不链接数据,因此d
未定义。正如Lars指出的,元素本身在事件处理程序中可以作为this
访问,并且可以通过d3转换为一个选择。如果您想操作它,请选择(this)
。您可能希望在尝试了解API文档之前先了解一下。
<svg>
<g id="edges"></g>
....
<g id="nodes">
<circle class="thing1"/>
<circle class="thing2"/>
....
</g>
</svg>