-1

我必须制作一个函数来获取所有圆形元素并使其可点击。使用我的代码,我只能单击创建的最后一个节点,但我不明白为什么。你能帮我吗?我使用 d3 库,这就是我的代码:

var allCircles = vis.selectAll('circle');

allCircles.on('click', function(){
    /* make the same stuff depending from the circle clicked */
});

如果你需要更多的解释问我。

非常感谢你帮助我!`

4

2 回答 2

1

最好在圆圈的(父)容器元素上添加事件侦听器。这意味着您有这样一个元素,例如<g>,您可以在其中添加侦听器。

var circleContainer = /* find your g element that contains the circles here */;

circleContainer.on('click', function(){
    // d3.event.target is the clicked circle
    d3.select(d3.event.target).attr("fill", "blue");
});

如果您更熟悉 jQuery,则该概念在此处称为“委托事件”

于 2013-10-22T08:40:25.037 回答
0

我不使用 d3 库,我从未听说过它,但我可以不用

var circles=document.getElementsByTagName('circle');
function onclik() {
  //do stuff
}
for(var i=0;i<circles.length;i++){
  circles[i].setAttribute("onclick","onclik()")
}

我希望它有帮助!

于 2013-10-22T04:23:20.160 回答