简体   繁体   English

动态添加按钮 d3.js

[英]Dynamically add button d3.js

This seems like a really trivial question, but I cannot for the life of me find a satisfying answer.这似乎是一个非常微不足道的问题,但我终究无法找到令人满意的答案。

How do I add a button with a bound function WITHOUT hardcoding it into the page or string-ifying the "onclick" attribute?如何在不将按钮硬编码到页面或字符串化“onclick”属性的情况下添加具有绑定功能的按钮?

ie IE

some_div_selection.append("button").text("+").on("click", console.log("You clicked me"));

instead the only way I've seen people do this is相反,我看到人们这样做的唯一方法是

some_div_selection.append("button").attr("onclick", "foobar()").text("+")

Which seems very clunky and brittle.这看起来非常笨重和脆弱。 Do I need to give the button some kind of data or what?我需要给按钮某种数据还是什么?

I'm a D3 programmer and I must say that in all those years I never saw a single D3 code using the approach you claim is the only one you have seen, which is setting the onclick attribute:我是一名 D3 程序员,我必须说,在这些年里,我从未见过一个 D3 代码使用你声称是你唯一见过的方法,即设置onclick属性:

selection.attr("onclick", "foo()")

It does work, but that's not idiomatic D3.它确实有效,但这不是惯用的 D3。 In D3, we use the on method.在 D3 中,我们使用on方法。 However, the problem with your first snippet is that it's calling the function immediately:但是,您的第一个代码段的问题在于它会立即调用该函数:

 d3.select("body").append("button").html("Click me").on("click", console.log("you clicked me"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

You can see that the console displays "you clicked me" without any click.可以看到控制台显示“you clicked me” ,没有任何点击。 So, for that to work, we should not call the function.所以,为了让它起作用,我们不应该调用这个函数。 Funnily enough, console.log accepts 3 arguments, have a look at what happens if we don't call console.log :有趣的是, console.log接受 3 个参数,看看如果我们不调用console.log会发生什么:

 d3.select("body").append("button").html("Click me").on("click", console.log);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

Now console.log works when you click the button, because you passed it as the function reference.现在,当您单击按钮时, console.log会起作用,因为您将它作为函数引用传递了。 However, the first value is undefined because you didn't pass any string to console.log .但是,第一个值是undefined的,因为您没有将任何字符串传递给console.log

That being said, what you want is:话虽这么说,你想要的是:

 d3.select("body").append("button").html("Click me").on("click", () => { console.log("you clicked me") });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

Now you're passing a proper function to the click event, which will be called when you click.现在您将适当的函数传递给click事件,单击时将调用该函数。

What happens when you:当您执行以下操作时会发生什么:

some_div_selection.append("button").text("+").on("click", function(){console.log("You clicked me")});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM