[英]Adding arguments in dynamically created buttons
I have been struggling with an issue which perhaps is really simple. 我一直在努力解决一个可能非常简单的问题。 The wider context is a force directed graph in which I want to generate a series of filtering buttons dynamically whose categories come from a JSON file from an external API. 较宽泛的上下文是一个强制导向图,其中我想动态生成一系列过滤按钮,其类别来自外部API的JSON文件。 I want to assign each category as an argument in the call of the button, however I have not been able to do this via JS. 我想将每个类别分配为按钮调用中的一个参数,但是我无法通过JS做到这一点。 The code that relates to that part is: 与该部分相关的代码是:
//Create TA nodes buttons dynamically
for(var ta_name in ta_nodes) {
d3.select("#controls").append("button").on("click", filterNetwork(ta_nodes[ta_name].ta_name)).html(ta_nodes[ta_name].ta_name);
}
function filterNetwork(thematic_area_filtered) {
simulation.stop();
[...]
}
Any ideas on how I could generate the button while passing ta_nodes[ta_name].ta_name to the function? 关于在将ta_nodes [ta_name] .ta_name传递给函数时如何生成按钮的任何想法?
Thanks! 谢谢!
I did a workaround to solve this as follows: 我做了一个变通办法来解决此问题,如下所示:
// Adding TA buttons from nodes via a text
var ta_discursive_nodes_buttons = d3.select("#controls")
.append("div")
.attr("class", "ta_discursive_nodes_buttons")
.selectAll("div")
.data(ta_discursive_nodes)
.enter()
.append("div")
.text(function(d){
return d.ta_name;
});
// Adding event handler
ta_discursive_nodes_buttons.on("click", function(d) {
//alert(d.ta_name);
filterRelationshipsByThematicArea(d.ta_name);
});
Probably not the most elegant solution, but it works! 可能不是最优雅的解决方案,但它可行! I hope it can be useful for other people :-) 我希望它对其他人有用:-)
Your code (in your question, not in your answer) has some problems: 您的代码(在您的问题中,而不是您的答案中)存在一些问题:
Do not pass the value of the function as the listener. 不要将函数的值作为侦听器传递。 When you do this: 执行此操作时:
.on("click", foo())
You are passing the returned value of foo
, not calling foo
on click, which would be: 您正在传递foo
的返回值 ,而不是单击click时调用foo
,这将是:
.on("click", foo)
Or, in the case that foo
has arguments: 或者,在foo
具有参数的情况下:
.on("click", function(){ foo(bar) })
You cannot chain your function and html()
the way you did. 您不能像以前那样将函数和html()
在一起。
That being said, use an "enter" selection, setting the listeners. 就是说,使用“输入”选择来设置侦听器。 Here is a basic example: 这是一个基本示例:
var data = ["foo", "bar", "baz"]; var body = d3.select("body"); var buttons = body.selectAll(null) .data(data) .enter() .append("button") .text(function(d, i) { return "Button " + (i + 1) }) .on("click", function(d) { displayValue(d) }); function displayValue(value) { alert("This button has the datum '" + value + "'") }
button { margin: 2px; padding: 6px; }
<script src="https://d3js.org/d3.v4.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.