dc.js图表.on函数报错:dcChart.on不是一个函数问题求助
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 theon()method that belongs to dc.js chart objects.
Solution 1: Use dc.js's Built-in Chart Registry (Recommended)
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

