You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

D3.js v3中下拉选中元素时调用tooltip.show报错的问题求助

解决方案

问题核心在于d3-tip的show方法需要绑定对应的数据和DOM元素上下文,直接用.call(tooltip.show)没有正确传递必要参数,导致报错。以下是两种可行的修改方式:

方式一:模拟鼠标悬停事件

既然鼠标悬停时tooltip.show能正常执行,直接给选中元素手动派发mouseover事件即可:

function showSelectedMunic(munic_info_id){
  const svg = d3.select("#map1")
  svg.selectAll(".municipalities path")
    .filter(function(d) { return d.id == munic_info_id })
    .each(function() {
      d3.select(this).dispatch('mouseover');
    })
}

方式二:直接调用tooltip.show并传参

先确保能获取到tooltip实例(可以通过全局变量或闭包保存),然后在选中元素的上下文中调用show方法并传入对应数据:

第一步:修改初始化函数保存tooltip实例

// 全局对象存储tooltip实例,避免依赖DOM内部属性
const tooltipInstances = {};

function initialize_map(id){
  const svg = d3.select(id).append("svg")
    .attr("width", map_width)
    .attr("height", map_height)

  const tooltip = d3.tip()
              .attr('class', 'd3-tip')
              .attr("id", "tool-" + id)
              .offset([-5, 0])
              .html(d => get_location_info(d, "tool-" + id))

  svg.append("g")
    .attr("class", "municipalities")
    .selectAll("path")
    .data(municipalities)
    .enter()
    .append("path")
    .attr("id", d => d.GEO_ID)
    .attr("d", path)
    .on('mouseover', tooltip.show)
    .on('mouseout', tooltip.hide)

  svg.call(tooltip)
  // 将实例存入全局对象,方便后续调用
  tooltipInstances[id] = tooltip;
}

第二步:修改showSelectedMunic函数

function showSelectedMunic(munic_info_id){
  const tooltip = tooltipInstances['#map1'];
  const svg = d3.select("#map1")
  
  svg.selectAll(".municipalities path")
    .filter(d => d.id == munic_info_id)
    .each(function(d) {
      // 在当前元素上下文调用show方法,传入对应数据
      tooltip.show.call(this, d);
    })
}

注意:不要直接用d3.select('#tool-map1')获取的DOM元素调用show,因为show是d3-tip实例的方法,而非DOM元素的方法。

内容的提问来源于stack exchange,提问作者Moe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 14:17:47