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

dc.js图表.on函数报错:dcChart.on不是一个函数问题求助

Fixing "Uncaught TypeError: dcChart.on is not a function" in dc.js

Hey there, let's break down why you're hitting this error and how to fix it quickly.

The Root Cause

The error pops up because you're trying to call dc.js's on() method on raw DOM elements, not actual dc.js chart instances. Here's the breakdown of what's wrong in your code:

  • d3.selectAll("div.mychart") returns a D3 selection of plain DOM nodes (the <div> elements holding your charts).
  • When you loop through this selection with _.each, you're iterating over those basic DOM elements—they don't have the on() method that belongs to dc.js chart objects.

dc.js automatically keeps track of every chart you create in the dc.charts array. This is the most reliable way to access all your chart instances:

// Iterate over all registered dc.js charts
_.each(dc.charts, function(dcChart) {
  dcChart.on("filtered", function(chart, filter) {
    // Clear existing map layers
    map.eachLayer(function(layer) {
      map.removeLayer(layer);
    });
    // Redraw the map
    drawMap();
  });
});

// Render all charts
dc.renderAll();

Solution 2: Access Charts via DOM Elements (Alternative)

If you specifically need to target charts in certain DOM containers, dc.js attaches chart instances to their corresponding DOM nodes via the __chart__ property (note this is an internal property, so Solution 1 is preferred for long-term reliability). Here's how to use it:

// Update the class of your chart containers first
d3.selectAll("div.mychart").attr("class", "yourchart");

// Iterate over the actual DOM nodes from the selection
_.each(d3.selectAll("div.yourchart").nodes(), function(domElement) {
  // Pull the dc.js chart instance from the DOM element
  var dcChart = domElement.__chart__;
  
  // Double-check we're working with a valid dc.js chart
  if (dcChart) {
    dcChart.on("filtered", function(chart, filter) {
      map.eachLayer(function(layer) {
        map.removeLayer(layer);
      });
      drawMap();
    });
  }
});

dc.renderAll();

Key Takeaway

Always keep this in mind: D3 selections give you DOM elements, not dc.js chart objects. Stick to dc.js's own APIs (like dc.charts) to interact with your chart instances, and you'll avoid this type of mismatch error.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:44:12