将“onclick”事件附加到D3图表背景 [英] Attaching 'onclick' event to D3 chart background
问题描述
我有一个D3直方图图表,我在其上附加了一个'onclick'事件到栏:
I have a D3 histogram chart, onto which I have attached an 'onclick' event to the bars:
...
var bar = svg.selectAll(".bar")
.data(data)
.enter().append("g")
.attr("class", "bar")
.attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; })
.on('mouseover', tip.show)
.on('mouseout', tip.hide)
.on('click', function(d,i){ //do stuff });
...
我也想附加一个'onclick'事件到图表的背景(即在图表中的任何地方,不是一个酒吧),但我有麻烦这个。我已尝试以几种方式附加事件,但在每种情况下,此新事件似乎覆盖了我的bar点击:
This works exactly as expected. I would also like to attach an 'onclick' event to the background of the chart (ie. everywhere in the chart that is not a bar), but I am having trouble with this. I have tried attaching the event in a couple ways, but in every case, this new event seems to override my bar-click:
一些尝试:
$("svg:not('.bar')").on("click", function(){ //do stuff });
$("g:not('.bar')").on("click", function(){ //do stuff });
var svg = d3.select("#histogram_block").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.on("click", function(d,i){
if (d) { //do stuff}
else { //do stuff }
};
我假设有一种方法可以添加
I am assuming there is a way to add the event handler to the SVG object when it is initialized, but I don't know the correct way to go about this.
推荐答案
在SVG对象被初始化时,我不知道正确的方法。事件实际上没有被覆盖,但是两者都被触发 - 用于SVG和bar的 onclick
处理程序。为了防止这种情况,使用 .stopPropagation()
方法(请参阅文档)。代码看起来像这个:
The event isn't actually overridden, but both are triggered -- the onclick
handler for the SVG and for the bar. To prevent this, use the .stopPropagation()
method (see the documentation). The code looks like this:
rect.on("click", function() {
console.log("rect");
d3.event.stopPropagation();
});
Complete example here. Compare with the behaviour with stopping the propagation of the event here.
这篇关于将“onclick”事件附加到D3图表背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!