首页 > 解决方案 > d3.js selectAll 用于路径

问题描述

我正在尝试获得一个 D3.js 交互式地图,在悬停在某个自治市(分为 svg 路径)上时,将返回该自治市的名称和逃生室主题的数量。但是,我无法使用 selectAll("path") 或任何变体来处理它。

这是我的代码:

d3.json("data/seoul_municipalities_topo_simple.json", function(error, data) {
  var features = topojson.feature(data, data.objects.seoul_municipalities_geo).features;
  seoulmap.selectAll("path")
    .data(features)
    .enter().append("path")
    .attr("class", function(d) {
      console.log();
      return "municipality c" + d.properties.SIG_CD
    })
    .attr("id", function(d) {
      return d.properties.SIG_KOR_NM
    })
    .attr("d", path); /* the path variable holds the geoPath from my topojson file*/
});

//tooltip displays
var mouselocation;
var tooltip = d3.select(".tooltip");
var mappath = d3.selectAll("path"); /* this doesn't work */

mappath.on('mouseenter', function() {
  tooltip.style('display', 'block');
  let textID = this.id;
  tooltip.select(".tooltip-city")
    .html("<strong>" + textID + "</strong></br>");

  tooltip.select(".tooltip-num")
    .html("# of Themes: ");
}).on('mousemove', function() {
  mouselocation = d3.mouse(d3.select('body').node());
  tooltip.style("left", mouselocation[0] + 160 + "px")
    .style("top", mouselocation[1] + 10 + "px");
}).on('mouseleave', function() {
  tooltip.style('display', 'none');
});

当我在控制台上运行我的网站时,svg 中的每个元素都被划分为包含 .municipality 类的路径。通过它进行选择也不起作用。但是,如果我将选择器替换为其他东西,比如“svg”,它就像一个魅力。我不确定我在这里做错了什么?

(我正在使用 D3.js v4!)

标签: javascriptd3.js

解决方案


推荐阅读