我试图选择 html 表单中的所有按钮以添加一些 onclick 事件,但我仍然有“d”未定义错误,有人可以解释我错在哪里吗?
这里是 html 代码:
<Form id="menu_f">
<input type="file" id="import_f" value="data.json" class="__KR_VIEW">
<input type="button" id="import" value="Import Data" class="__KR_VIEW">
<input type="button" id="edit_kr" value="Edit KR" class="__KR_VIEW" >
....(a lot of input)
</form>
这里是 d3 代码:
d3.select("#menu_f").selectAll("input").filter(function(d){return d.attr("type") == "button"}).on("click",function(d){menuHandler(d.attr("id"))});
这是我得到的错误:
TypeError: d is undefined
谢谢!
最佳答案
虽然@AdamBotley的答案是正确的,但更d3
的方法是:
d3.select("#menu_f")
.selectAll("input")
.filter(function(d) {
return (this.type === "button");
})
...
在 d3
函数中,this
通常始终引用所选元素。
完整代码:
<!DOCTYPE html>
<html>
<head>
<script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
</head>
<body>
<form id="menu_f">
<input type="file" id="import_f" value="data.json" class="__KR_VIEW" />
<input type="button" id="import" value="Import Data" class="__KR_VIEW" />
<input type="button" id="edit_kr" value="Edit KR" class="__KR_VIEW" />
</form>
<script>
d3.select("#menu_f")
.selectAll("input")
.filter(function(d) {
return (this.type === "button");
}).each(function(d){
console.log(this);
});
</script>
</body>
</html>
关于javascript - 使用 d3 通过类型过滤输入表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34204442/