我正在使用d3散点图。我连接到数据库,最初我在图表上说了3个点。每个点代表一张纸,x轴为年份,y轴为引用次数。现在,当我单击一个点时,该论文引用的论文就会显示在图形上。到目前为止,我已经完成了所有上述操作,但是现在的问题是,尽管当我单击点时,相关的文件会显示在图形上,但是当我单击这些点时,什么也不会发生。所以我还没有设法将我的Json数据绑定到新点。以下是相关代码:
// initial connection to display papers
d3.json("connection4.php", function(error,dataJson) {
dataJson.forEach(function(d) {
d.YEAR = +d.YEAR;
d.counter = +d.counter;
console.log(d);
})
//baseData is the original data that I dont want to be replaced
baseData = dataJson;
// draw dots
var g = svg.selectAll(".dot")
.data(baseData)
.enter()
.append("circle")
.attr("class", "dot")
.attr("r", 3.5)
.attr("cx", function(d) {return x(YearFn(d))})
.attr("cy", function(d) {return y(Num_citationsFn(d))})
.style("fill","blue")
.on("click", function(d, i) {
d3.json("connection2.php?paperID="+d.ID, function(error, dataJson) {
console.log(dataJson);
dataJson.forEach(function(d) {
d.YEAR = +d.YEAR;
d.counter = +d.counter;
console.log(d);
baseData.push(d);
})
var g = svg.selectAll(".dot")
.data(baseData)
.enter()
.append("circle")
.attr("class", "dot")
.attr("r", 3.5)
.attr("cx", function(d) {return x(YearFn(d))})
.attr("cy", function(d) {return y(Num_citationsFn(d))})
.style("fill", "red")
})
我在php文件中的查询很好,因为我可以看到它们返回了正确的数据,所以我认为我的主要问题是将第二次连接中的Json数据绑定到新点。我想知道有人能阐明我该怎么做吗。我是d3的新手,因此感谢您提供任何反馈!提前致谢
最佳答案
我认为问题很简单,您没有将"click"
事件绑定到新创建的节点。
更换线
// draw dots
var g = svg.selectAll(".dot")
.data(baseData)
.enter()
.append("circle")
.attr("class", "dot")
.attr("r", 3.5)
.attr("cx", function(d) {return x(YearFn(d))})
.attr("cy", function(d) {return y(Num_citationsFn(d))})
.style("fill","blue")
.on("click", function(d, i) {
...
})
通过
function clickHandler (d,i){
...
}
// draw dots
var g = svg.selectAll(".dot")
.data(baseData)
.enter()
.append("circle")
.attr("class", "dot")
.attr("r", 3.5)
.attr("cx", function(d) {return x(YearFn(d))})
.attr("cy", function(d) {return y(Num_citationsFn(d))})
.style("fill","blue")
.on("click", clickHandler); //clickHandler is referenced here, instead of the original anonymous function
并在您的新创建的节点中添加一个
.on("click", clickHandler);
调用,即在clickHandler函数本身中: ///add linked dots
var g = svg.selectAll(".dot")
.data(baseData)
.enter()
.append("circle")
.attr("class", "dot")
.attr("r", 3.5)
.attr("cx", function(d) {return x(YearFn(d))})
.attr("cy", function(d) {return y(Num_citationsFn(d))})
.style("fill", "red")
.on("click", clickHandler); //click handler is *also* called here