用 d3js 抓取元素

Grab the element with d3js

我正在尝试学习 d3js 库。遇到点击捕获table的TD元素的问题。我一般都是这样用的

window.addEventListener("load", function(){
    document.getElementById("table_id").addEventListener("click",function(e){
            var elem = e.target || e.srcElement;

            if(elem.nodeName != "TD") return;

...
    }
...

所以我需要在 d3js 中做类似的事情。但我不知道如何替换 .target 和 .srcElement 方法。 我有什么

d3.select(#table_id).on('click',function(){
    var elem = ???

this 我有我的 table。在 d3.event 这样的信息中 click clientX=327, clientY=129d 未定义

请帮我抓取 var.

中的 TD 元素

D3js非常灵活,不需要每次都用d3.event.target

如您所问,您的代码中遗漏了一些细节:

1. 选择

d3 中有两个 selection 函数:

d3.select() 它获取或查找特定的 tagelementclasstag id,例如:

d3.select('div') return 第一个 div 或 d3.select('.active') 发现标签有 class 命名为活动。在你的情况下,你应该使用 d3.select('#table_id') 你错过了 select 函数中的单引号。

下一个 d3 selection 函数是 d3.selectAll() 作用类似于 d3.select() 但区别在于此函数 select 所有参数,例如:

d3.selectAll('p') return 所有 p 标签或所有 Id 或 classes 都作为参数获取。

2. 这个和d的区别

this 是用于 select 特定标记的参数,您尝试 select 或在其上做一些事情,并且在 selectAll 函数中更有用,因为您不知道哪个标签 selected.

d 是一个包含所有属性和事件的对象或 DOM

所以我更改了您的代码,希望它能帮助您更好地学习 d3

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

            var elem=d3.select(this);
            if(elem.attr("name")!=="TD")
                  return;

});

更多信息here