将数据绑定到 d3 中的新元素
Binding data to new elements in d3
我正在使用 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
相关文章:
- 触摸移动时切换到新元素
- 将按钮添加到新元素中
- 如何在javascript上向数组的对象添加新元素
- 如果数组仍在执行,async.forEach()将运行我添加到数组中的新元素
- 剑道UI下载列表:如何动态添加新元素
- 在DIV中动态插入HTML并访问新元素
- 使一个新元素在某个时间出现
- 单击不适用于新元素
- 动态添加新元素并更改其内容
- 没有为Ajax添加的新元素注册Jquery事件
- css在新元素上的转换
- 如何在不创建新元素的情况下修改 DOM 元素的位置
- jquery添加新元素
- 如何在遍历表和添加新元素时获得tr的索引
- PNG修复新元素
- 将点击事件绑定到新元素&使得ID'是独一无二的
- 从HTML表单中获取计算得到的JavaScript数据,并将其作为新元素添加到相同的表单操作中以使用PHP保存
- jQuery没有为具有新id的新元素执行代码
- jQuery倒计时-应用于通过AJAX/PHP加载的新元素
- 在元素内部创建新元素