2

我有一个 DAG 的 D3.js 可视化,使用强制导向布局。有时我想更改某些节点的颜色。到目前为止,我已经在点击监听器中使用this

function clickNode(node) {
    d3.select(this).attr("fill", nodeHighlightColour);
}

但是,现在我想更改由侦听器调用的函数中的节点颜色,而不是侦听器本身。它必须是一个单独的函数的原因是我想“突出显示”一系列节点,从被点击的节点回溯,所以我需要tracePath递归调用函数 ()。

如果我tracePath从侦听器调用,我在尝试时会收到“未定义函数”运行时错误d3.select(this).attr("fill")。我猜这是因为this不再在范围内。我可以将node对象传递给tracePath,但这是节点数据而不是 DOM 元素。如何仅使用绑定到它的数据对象来获取 DOM 元素?

编辑: 正如我在对 Felix Kling 的评论中所写,我不能简单地传递thistracePath. 这将适用于第一个节点,但我仍然必须递归调用该函数。tracePath到目前为止,这是我的功能:

// Trace the back from a node - node_el is "this", node is the node data
function tracePath(node_el, node) {
    var this_id = node.id;

    if (node.logic == null) {
            console.log("Highlighting!");
            // Using "this" to change colour
            d3.select(node_el).attr("fill", nodeHighlightColour);
    }
    // Look for edges that point to this node
    for (var i=0; i<edges.length; i++) {
            var e = edges[i];
            if (e.target == this_id) {
                    var next_node = None;

                    // Get the node at the source of the edge
                    for (var j = 0; j<nodes.length; j++) {
                        if (nodes[j].id == e.source) {
                            next_node = nodes[j];
                        }
                    }
                    // Recursively trace back from that node
                    if (next_id != None) {
                            // How do I get the DOM element to pass to tracepath?
                            tracePath(???, next_node);
                    }
            }
    }
}
4

1 回答 1

0

感谢 Felix Kling 对此的回答!正如他所建议的,我id向每个 SVG 圆形元素添加了一个与节点数据 ID 相同的元素,如下所示:

 circle = d3.select('#graphics').append("g").selectAll("circle")
         .data(force.nodes())
         .enter().append("svg:circle")
         .attr("id", function(d) {
              return d.id;
         })
         .on("click", clickNode)

Then, I could access the DOM element using the node id. Here is my finished tracePath function:

// Trace the path back from a node
function tracePath(node_el, node) {
    var this_id = node.id;
    console.log("in tracepath");
    if (node.logic == null) {
            console.log("Highlighting!");
            d3.select(node_el).attr("fill", nodeHighlightColour);
    }
    console.log("this_id:", this_id);
    // Look for edges that point to this node
    for (var i=0; i<edges.length; i++) {
            var e = edges[i];
            if (e.target.id == this_id) {
                    console.log("edge from ", e.source.name);

                    // Recursively trace back from that node
                    var next_el = document.getElementById(e.source.id);
                    tracePath(next_el, e.source);
            }
    }
}

I also noticed that e.target (where e is an edge) gives me the target node itself, not just the id, so I didn't need to search through the nodes.

于 2013-08-12T21:00:00.947 回答