我正在 d3 中编写一个项目,其中我有一个包含两个外部 javascript 文件的 html 页面,例如 script_1.js 和 script_2.js.
我需要从 script_1.js 注册一个事件侦听器,从 script_2.js 注册另一个事件侦听器,用于选择元素上的更改事件.目前我的 html 中有这一行:
I'm writing a project in d3 in which I have an html page incorporating two external javascript files, say script_1.js and script_2.js.
I need to register one event listener from script_1.js and another from script_2.js for the change event on a select element.
At present I have this line in my html:
<select id="timebasis" class="selector" onchange="selectIndexSp(this),selectIndexBt(this)">
其中 selectIndexSp(object) 和 selectIndexBt(object) 分别在 script_1.js 和 script_2.js 中定义.我根本不喜欢这种方法,我想知道如何在 d3 中而不是在 html 文件中执行相同的任务,我知道这不是一个好习惯.
where selectIndexSp(object) and selectIndexBt(object) are defined respectively in script_1.js and script_2.js. I don't like this approach at all, and I'd like to know how to perform the same task in d3 rather than in the html file, which I know isn't a good practice.
提前致谢!
您可以为事件名称添加命名空间,例如:
You can add a namespace to the event name like:
d3.select("#timebasis")
.on("change.sp", listenersp)
.on("change.bt", listenerbt);
参见:https://github.com/mbostock/d3/wiki/Selections#wiki-on
如果事件侦听器已在选中的元素,现有的监听器在新的监听器之前被移除添加了监听器.为同一事件注册多个侦听器类型,类型后面可以跟一个可选的命名空间,例如click.foo"和click.bar".要删除侦听器,请将 null 作为听众.
If an event listener was already registered for the same type on the selected element, the existing listener is removed before the new listener is added. To register multiple listeners for the same event type, the type may be followed by an optional namespace, such as "click.foo" and "click.bar". To remove a listener, pass null as the listener.
函数被传递当前数据 d
和索引 i
,this
上下文作为当前 DOM 元素.看起来您的两个函数期望 DOM 元素作为参数?在这种情况下,它看起来像:
The functions are being passed the current datum d
and index i
, with the this
context as the current DOM element. It looks like your two function expect the DOM element as argument? In that case it would look like:
d3.select("#timebasis")
.on("change.sp", function() { selectIndexSp(this); })
.on("change.bt", function() { selectIndexBt(this); });
这篇关于如何将多个外部侦听器注册到 d3 中的同一选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!