【问题标题】:D3.JS get reference to bound data of clicked objectD3.JS 获取对被点击对象的绑定数据的引用
【发布时间】:2013-01-25 00:48:30
【问题描述】:

我是 javascript 和 D3.js 的新手

我正在使用 https://gist.github.com/4062045 的力有向图示例

我需要获取对被点击的圆形元素的绑定数据的引用,以便我可以添加一个链接。

我在圆圈的点击处理程序中有以下代码行:

d3.select(this).each(function(d){console.log(d)});

我可以将对象打印到控制台,但我不知道如何获取对该对象的引用,以便将其推送到链接对象中,例如:

{source: <reference to node should go here>, target: some_other_node}

感谢您的帮助!

【问题讨论】:

    标签: javascript d3.js force-layout


    【解决方案1】:
    circles.on('click', datum => {
      console.log(datum); // the datum for the clicked circle
    });
    

    # selection.on(typenames[, listener[, capture em>]])

    当在选定节点上调度指定事件时,将为每个选定元素评估指定的侦听器,并传递当前数据 (d)、当前索引 (i) 和当前组 (nodes),其中this 作为当前的 DOM 元素。

    【讨论】:

    • 感谢您为我指明正确的方向 Wex。您的评论让我意识到我只需要从 selection.on 中获取对绑定数据的引用,而不是尝试使用“this”从事件处理程序中获取引用。
    • 这是评论,不是答案。我正在寻找相同的信息,但这个答案没有帮助,只指向链接
    • 更好 :) 但为什么链接在 # 符号而不是整行?在使用# 作为链接之前,我从未见过这种做法
    【解决方案2】:

    为了其他新手的利益,这就是我解决这个问题的方法:

    //Register the event handler with you selection
    myselection.on("click", click);
    
    //Obtain reference to data of currently clicked element by obtaining the first argument of      the event handler function
    
    function click(element){ 
        console.log(element); 
    }
    

    【讨论】:

    • 请注意,第一个参数是 datum 而不是 elementthis 是 DOM 元素。
    【解决方案3】:

    这是我的解决方案:

    /* CSS used in Javascript snippet */
    .source { 
      stroke-width: 3px !important;
      stroke-opacity: 1;
      stroke: #0f0;
    }
    
    .target { 
      stroke-width: 3px !important;
      stroke-opacity: 1;
      stroke: #f00;
    }
    
    
    // this goes inside the d3.json call
    node.on("mouseover", function() {
      idx = this.__data__.index
      for (i = 0; i < graph.links.length; i++) {
        if (graph.links[i].source.index == idx) {
          link[0][i].classList.add("source");
        }
        else if (graph.links[i].target.index == idx) {
          link[0][i].classList.add("target");
        }
        else {
          link[0][i].classList.remove("source");
          link[0][i].classList.remove("target");
        }
      }
    });
    

    这个想法是,在触发给定事件时,您将查看链接列表,并突出显示(添加一个类)到其源或目标与给定节点数据中找到的索引匹配的每个链接。它可能没有完成 d3 能够做的所有事情,但它不需要额外的库,而且我正在快速突出显示我的源/目标链接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-14
      • 2012-04-12
      • 2020-02-21
      相关资源
      最近更新 更多