Jos*_*oss 2 javascript svg event-bubbling dom-events d3.js
我有一个svg结构,里面有一些形状.我想在单击一个形状时触发一个事件,而在单击一个svg时触发另一个.问题是SVG事件总是被触发.
为了防止这种情况,我禁止事件从形状冒泡.此外,我试图用d3禁用该事件,但似乎无法正常工作.还尝试使用本机javascript代码禁用事件.
超简单代码的一个例子是:
svg结构
<svg id="canvas" xmlns="http://www.w3.org/2000/svg" version="1.1">
<g>
<circle class="shape" r="10" cx="10" cy="10">
</g>
</svg>
Run Code Online (Sandbox Code Playgroud)
javascript代码
d3.select('#canvas').on('click',svgClickEvents);
d3.selectAll('.item')
.on("mouseover",mouseoverItem)
.on('mouseleave',mouseleaveItem);
//click
d3.selectAll('.item',function(){
//when an item is clicked, svgClickEvents must not be fired
d3.select('#canvas').on('click',null); //this should remove the event listener
//also tried with getElementById('canvas').removeEventListener('click',clickEvents,false);
d3.select(this)
.on("click",function() {
d3.event.stopPropagation();
console.log("click circle")
});
});
Run Code Online (Sandbox Code Playgroud)
我知道事件没有被禁用,因为我从clickEvents函数获取console.log()文本警报.
谢谢.
在这种情况下,语法:
d3.selectAll('.classname', function() { ... });
Run Code Online (Sandbox Code Playgroud)
在d3.js中不起作用 相反,你应该使用类似的东西:
d3.selectAll('.classname').each(function() { ... });
Run Code Online (Sandbox Code Playgroud)
所以在上面的代码中,这应该工作:
d3.selectAll('.item')
.each(function(){
//when an item is clicked, svgClickEvents must not be fired
d3.select('#canvas').on('click', null); //this should remove the event listener
d3.select(this).on("click",function() {
d3.event.stopPropagation();
console.log("click circle");
});
});
Run Code Online (Sandbox Code Playgroud)