英文:
Selecting a single element in D3 .join
问题
我有以下的代码,它使用mouseover和mouseout函数创建一系列点。然而,我无法弄清楚如何引用单个“point”实例 - 使用变量point会选择所有点:
settings.g.selectAll("node")
.data(positions)
.join(
enter => {
let point = enter.append("circle")
.attr("cx", d => d.x)
.attr("cy", d => d.y)
.attr("stroke-opacity", 0.5)
.on('mouseover', (d) => {
pointMouseOver(d)
point.attr("stroke-opacity", 1) //这会选择所有点,而不仅仅是一个
})
.on('mouseout', (d) => pointMouseOut(d))
}
)
英文:
I have the following code which creates a series of points with mouseover and mouseout functions. However, I cannot figure out how to reference a single "point" instance - using the variable point selects all of them:
settings.g.selectAll("node")
.data(positions)
.join(
enter => {
let point=enter.append("circle")
.attr("cx", d => d.x)
.attr("cy", d => d.y)
.attr("stroke-opacity", 0.5)
.on('mouseover', (d)=> {
pointMouseOver(d)
point.attr("stroke-opacity", 1) //THIS SELECTS ALL POINTS, NOT JUST 1
})
.on('mouseout', (d)=>pointMouseOut(d))
}
)
答案1
得分: 1
point
变量是输入选择, 在你的情况下包含多个元素。
要获取选定的元素,请使用this
或者,因为你使用了箭头函数:
.on('mouseover', (d, i, n) => {
d3.select(n[i]).attr("stroke-opacity", 1)
})
在最近版本的D3中,你可以在监听器中使用event.currentTarget
:.on('mouseover', (event, d) => { ... })
。
英文:
The point
variable is the enter selection, which in your case contains several elements.
To get the selected element use this
or, since you have an arrow function:
.on('mouseover', (d, i, n)=> {
d3.select(n[i]).attr("stroke-opacity", 1)
})
In recent versions of D3 you can use event.currentTarget
in the listener: .on('mouseover', (event, d) => { ... })
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论