使用 d3.js 在同一个点击事件上调用两个函数 [英] Calling two functions on same click event with d3.js

查看:31
本文介绍了使用 d3.js 在同一个点击事件上调用两个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道是否可以使用 d3.js 在同一个事件上调用两个单独的函数?我知道你可以在 JavaScript 中通过用分号分隔两者来做到这一点,但在我的特殊情况下没有成功做到这一点.我正在使用带有工具提示的力布局图,并且有两个我想要使用的独立工具提示.鼠标悬停时,会出现一个工具提示,说明节点的名称,然后单击时,我想要第二个工具提示来显示其描述.尽管如此,我希望第一个工具提示消失.这是我正在使用的代码块:

 .on("click", describe_tip.show).on(鼠标悬停",tip.show).on(鼠标移出",tip.hide)

我想调用 tip.hidedescribe_tip.show 但不知道正确的语法.

任何建议或帮助将不胜感激.

解决方案

你可以将你想进行的两个函数调用包装在一个匿名函数中,例如

.on("点击", function(d){describe_tip.show(d);提示.隐藏(d);})

请注意,由于 describe_tip.showtip.hide 都需要数据 d 作为参数,因此您需要将其传递给它们.回想一下,当将匿名回调函数传递给 .on("click", callback) 时,D3 通过:

<块引用><块引用>

当前数据d和当前索引i,以this上下文作为当前DOM元素

回调函数(docs).

Does anybody know if it is possible to call two separate functions on the same event with d3.js? I know you can do this in JavaScript by just separating the two with a semicolon but have not been successful doing this with my particular case. I am using a force-layout graph with tool-tips and have two separate tool-tips that I want to use. On mouseover, a tool-tip appears saying the name of the node and then on click, I want a second tool-tip to show its description. On that click though, I would like for the first tool tip to go away. Here is the block of code that I am using:

         .on("click", describe_tip.show)
         .on("mouseover", tip.show)
         .on("mouseout", tip.hide) 

I want to call tip.hide along with describe_tip.show but do not know the correct syntax.

Any suggestions or help would be appreciated.

解决方案

You can wrap the two function calls you want to make in an anonymous function, e.g.

.on("click", function(d){
    describe_tip.show(d);
    tip.hide(d);
})

Note that since describe_tip.show and tip.hide both require data d as an argument, you need to pass that to them. Recall that when passing an anonymous callback function to .on("click", callback), D3 passes:

the current datum d and the current index i, with the this context as the current DOM element

to the callback function (docs).

这篇关于使用 d3.js 在同一个点击事件上调用两个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆