Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

javascript - d3js data binding enter then select an element to listen to

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);

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

Here the format of trainSelect items

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

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);

But I get this error

ERROR DOMException: Failed to execute 'querySelector' on 'Document': '#123596' is not a valid selector.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...