【问题标题】:Remove event listener with d3js not working使用 d3js 删除事件侦听器不起作用
【发布时间】:2013-05-29 12:59:40
【问题描述】:

我有一个 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>

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")
        });
});

我知道事件没有被禁用,因为我从 clickEvents 函数收到了onsole.log() 文本警报。

【问题讨论】:

    标签: javascript d3.js svg dom-events event-bubbling


    【解决方案1】:

    在这种情况下,语法:

    d3.selectAll('.classname', function() { ... });
    

    在 d3.js 中不起作用。相反,你应该使用类似的东西:

    d3.selectAll('.classname').each(function() { ... });
    

    所以在你上面的代码中,这应该可以工作:

    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");
            });
    });
    

    【讨论】:

      猜你喜欢
      • 2019-06-30
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 2018-09-04
      相关资源
      最近更新 更多