Javascript d3基于用户选择动态更新节点

Javascript d3基于用户选择动态更新节点,javascript,d3.js,Javascript,D3.js,我试图使用户能够单击force布局中的节点,并将数据集简化为这些节点及其关联链接 我已经做到了这一点 从179开始的部分 d3.select("#filterResults") .on("click", function() { //feed the indexes of the selected nodes into array var nodeArray = [] d3.selectAll("circle[fill=\"Red\"]"

我试图使用户能够单击force布局中的节点,并将数据集简化为这些节点及其关联链接

我已经做到了这一点

从179开始的部分

d3.select("#filterResults")
    .on("click", function() {

        //feed the indexes of the selected nodes into array
        var nodeArray = []
        d3.selectAll("circle[fill=\"Red\"]")
            .each(function(d, i) {
                    nodeArray.push(d3.select(this).attr("node-index"))              
            })

        //step2: loop through nodes array and return only those nodes that share
        //index with nodeArray into newNodes
        var newNodes = []
        nodes.forEach(function(nde, idx, list) {
            nodeArray.forEach(function(nde2, idx2, list2) {
                if (idx == nde2) {
                     newNodes.push(nde)   
                }
            })
        })

        //step3: loop through links array and return only those links that
        //have source or target as index of nodes in nodeArray
        var newLinks = []
        links.forEach(function(link, lidx, llist) {
            nodeArray.forEach(function(nde, idx, list) {
                if (link.source == nde || link.target == nde) {
                        newLinks.push(link)
                }
            })
        })
        alert(newLinks.length)

    })
就是我被困的地方,特别是第三步。我似乎无法从onclick函数中获取链接,不管有多少链接与所选节点相关联,警报都会在应该返回的位置返回零


最终,我想确定与所选数据集关联的节点和链接,然后更新数据集以反映新的数据集(如果可能的话)!只有一种方法能找到答案

一旦开始强制,源值和目标值将替换为相应的节点对象。因此,与其将链接源与节点索引进行比较,不如将其与节点进行比较

if (link.source == nodes[nde] || link.target == nodes[nde]) {
    newLinks.push(link)
}

if (link.source.index == nde || link.target.index ==nde) {
    newLinks.push(link)
}
更新

注意:源属性和目标属性的值最初可能是 指定为节点数组中的索引;这些将被替换为 调用start之后的引用

这是节点的示例结构

{
    fixed: 0,
    index: 12,
    label: "I am an information label",
    px: 287.64956227452404,
    py: 83.71383910494417,
    weight: 7,
    x: 287.7214898272057,
    y: 83.59069881862021
}
d3.select(“.node”).data()
将返回与该节点关联的数据,其中
node
是类名


有关d3强制布局的更多信息,请参见。

“相应的节点对象”?有没有办法让我看看这些物体,看看它们是由什么组成的?force是如何用这些节点对象取代我的起始数组的?如果我想获取阵列数据用于其他用途,该怎么办?我已经更新了小提琴和答案。希望能有所帮助。如果我在links数组中循环并返回link.source,并在声明var links=graph.links后直接使用这段代码,那么我会得到数值作为响应。如果在声明var-force后使用完全相同的循环,则返回一个对象数组。你能解释一下那里发生了什么事吗?它怎么能搞乱基础数据集?抱歉问了这么多问题,我只是想弄清楚原力到底在做什么……没关系。阅读force.start部分的第二和第三段。这篇文档解释了在施力后节点和链接数组是如何改变的。所以很困惑。所以我已经声明了我的节点和链接。然后我使用这些节点和链接启动了原力。启动后,我无法通过上一点中演示的常用方法引用节点和链接-通过链接循环以获取源属性(对节点的索引引用),现在不能使用link.source,现在必须是link.source.index(链接不再是数字-它们实际上是节点对象?)。但是,如果您查看,我可以在返回事件节点选择时查看原始节点数组吗?