gpt4 book ai didi

javascript - 通过使用不同的选择器选择一个元素来赋予一个元素多个事件处理程序

转载 作者:数据小太阳 更新时间:2023-10-29 05:18:16 25 4
gpt4 key购买 nike

我有几个“事件”类,涵盖了我的一些 svg 元素。我正在为每个类分配一个用于 mouseovermouseout 的事件处理程序,如果一个元素有多个类,我希望两个处理程序都触发。我该怎么做呢?似乎当我这样做的时候

d3.selectAll(".a-class")
.on("mouseover", function() {
// do A
})
.etc();

d3.selectAll(".another-class")
.on("mouseover", function() {
// do B
})
.etc();

然后,当我将鼠标悬停在具有两个类的元素上时,只有 B(第二个处理程序)触发,显然是因为它覆盖了第一个。有没有一种方法可以“附加”事件处理程序,而不是重新定义它?

最佳答案

根据 documentation ...

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".

因此,您可以通过将任意命名空间附加到每个处理程序来实现您想要的。

d3.selectAll(".a-class")
.on("mouseover.a", function() {
// do A
})
.etc();

d3.selectAll(".another-class")
.on("mouseover.b", function() {
// do B
})
.etc();

这有一个额外的好处,您可以在以后显式引用添加的事件处理程序(单独或为整个命名空间)以替换或删除它们。

关于javascript - 通过使用不同的选择器选择一个元素来赋予一个元素多个事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36333774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com