我正在使用 d3.js 在 SVG 容器上绘制一组圆圈。
我有一个eventList
。对于此列表中的每个元素,我画一个圆圈。我是这样做的。它有效:
var eventList = [
Object {stateId: 5},
Object {stateId: 6},
Object {stateId: 7},
];
for (var i = 0; i <= eventList.length-1; i++) {
var currEvent = eventList[i];
var myCircle = self.svgContainer.append("circle")
.attr("cx", i * 100)
.attr("cy", i * 100)
.attr("r", 5)
.attr("stroke-width", 0)
.attr("fill", "red");
}
我现在正在尝试向每个圈子添加点击行为。我想单击每个圆圈,根据事件列表中找到的数据将我带到特定的 URL。这是我要添加到上面循环中的内容:
myCircle.on({
"click": function() {
console.log("Hello! currEvent.stateId=", currEvent.stateId.toString());
console.log("currEvent = ", currEvent);
$state.go('myState', {
'stateId': currEvent.stateId
}
);
}
}
);
根据我的理解,这应该可行。但事实并非如此。它的作用是当我单击任何圆圈时运行 onclick 代码。此时,它会打印出 currentEvent.stateId
的值 - 它始终是最后一个!。因此,单击每个圆圈只会将我带到同一个 URL - 这只应在单击最后一个圆圈时发生。
如何使 onclick 代码在绘制该圆圈时使用 currentEvent 的值,而不是在实际触发单击时使用?这对我来说是个大问题。
最佳答案
问题是当您执行点击事件时,变量 currEvent
将具有最后一个值,这就是您的问题。
正确的方法是将数据绑定(bind)到圆圈。
var myCircle = svg.selectAll(".dots")
.data(eventList).enter().append("circle")//make as many circle as their are events in the eventList. This will bind the data to the circle.
.attr("class", "dots")//set a class to circle for selection to work
.attr("cx", function(d, i) {
return (i * 100)
})
.attr("cy", function(d, i) {
return (i * 100)
})
.attr("r", 5)
.attr("stroke-width", 0)
.attr("fill", "red");
现在向所有圈子注册点击事件。
myCircle.on({
"click": function(d) {
//here d will give the bound object
console.log("Hello! currEvent.stateId=", d.stateId.toString());
console.log("currEvent = ", d);
}
});
工作代码here
关于javascript - d3.js onclick 事件使用单击时而不是绘制时的变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36257763/