d3js数据绑定输入,然后选择一个要监听的元素 [英] d3js data binding enter then select an element to listen to
问题描述
我想从DOM中选择元素,并将它们悬停在鼠标事件上.
I would like to select elements from DOM and listen to mouse event when hover them.
我正在使用此库(链接示例)
I'm using this library ( example on link )
let trainSelect = svg.selectAll('.train-w-dir').data(schedules, function(d: ISchedule) {
if (d != undefined) {
return d.train;
}
});
trainSelect
.enter()
.select(/ELEMENT TO SELECT/) // instead of append a new dom element as in the example
.on('mouseover', tip.show)
.on('mouseout', tip.hide);
我想选择一个具有id
属性等于每个trainSelect
数组(EnterNode或占位符?)data.train
字段的DOM元素.因为我不需要附加新元素,而只需听取现有元素
What I would like to is to select a DOM element that have id
attribute equal to every trainSelect
array (EnterNode or placeholder ?) data.train
field. Because I don't need to append a new element, but just listen to existing elements
以下是trainSelect
个项目的格式
namespaceURI: "http://www.w3.org/2000/svg"
ownerDocument: document
__data__: {remp_dest: null, cap: 922, tp_des_r: "00:20:44+00:00", dest: 271015, descentes: 0, …}
_next: null
_parent: svg#svg8727
更新 我试图这样选择 trainSelect
UPDATE I tried to make selection like this trainSelect
.enter()
.each(elm => {
return d3.select(`#${elm.train}`);
})
.on('mouseover', tip.show)
.on('mouseout', tip.hide);
但是我得到这个错误
错误DOMException:无法在'Document'上执行'querySelector':'#123596'不是有效的选择器.
ERROR DOMException: Failed to execute 'querySelector' on 'Document': '#123596' is not a valid selector.
推荐答案
问题源于您的ID以数字开头.这使得使用CSS选择器或使用querySelector
The problem stems from your IDs starting with a number. This makes it harder to locator with a CSS selector or when using querySelector
您需要像这样逃避每个字符:
You would need to escape each character likes this:
document.querySelector("#\\31\\32\\33\\35\\39\\36")
这真的很丑,而且不太实用.我建议您在ID的开头附加一个字母.然后,您可以正常查找元素,而无需进行转义.
Which is really ugly and not very usable. I would recommend appending a letter to the start of your IDs. Then you can find the elements normally without the need for escaping.
这篇关于d3js数据绑定输入,然后选择一个要监听的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!