我正在尝试弄清楚如何更新 d3.js 图表。阅读完示例后,-这里有很好的解释:http://chimera.labs.oreilly.com/books/1230000000345/ch09.html#_ordinal_scales_explained - 我认为我确实理解了原理,但还不够深入。
以下代码在页面刷新并使用事件处理程序单击 div 后绘制 Jim 的气泡图 - 代码已简化:
jQuery(function($) {
root.plotData = function(selector, data, plot) {
return d3.select(selector).datum(data.slice(start=0,stop=10)).call(plot);
};
plot = Bubbles();
display = function(data) {
return plotData("#vis", data, plot);
};
return d3.csv(url, display);
});
现在我想更新图表:
$("#some_id").on("click",function(){
updateLabels = function() {
root.plotData = function(selector, data, plot) {
return d3.select(selector).datum(data.slice(start=10,stop=20)).call(plot);
};
plot = Bubbles();
display = function(data) {
return plotData("#vis", data, plot);
};
return d3.csv(url, display);
});
});
});
但是,除非我先刷新页面,否则不会从我的按钮调用显示函数。我对问题可能是什么有点困惑。 为什么第一次点击会渲染,但第二次却不会?
最佳答案
我的解决方案:
function clicked_eventHandler() {
// insert here code chart rendering based on Jim's force directed layout bubble charts
jQuery(function($) {
// removing all children from element id="vis"
var svg = d3.select("#vis");
svg.selectAll("*").remove();
// running the display function
the new dataset is created by slicing the data setting two variables
start and stop ( here for test purposes set to 0, 10 ). This allows to slice rows
out of a long csv file.
root.plotData = function(selector, data, plot) {
return d3.select(selector).datum(data.slice(start=0,stop=10)).call(plot);
};
plot = Bubbles();
display = function(data) {
return plotData("#vis", data, plot);
};
return d3.csv(url, display);
});
};
意识到我需要刷新页面来清除 id="vis",我决定通过选择 id="vis"并删除所有子项来启动该函数。现在,btn 单击事件(使用函数中每个不同参数动态创建的 btns)适用于每个 btn,而不仅仅是页面刷新。当然欢迎提出改进我的解决方案的建议。
关于javascript - 了解通过单击按钮而不是页面刷新来更新 d3.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31042876/