繁体   English   中英

SVG矩形单击事件监听器

[英]SVG rectangle click eventlistener

我已经按照以下方式绘制了svg矩形,并尝试通过以下方式向其添加click事件。但是,代码无法正常工作。 我要去哪里错了?

var enterElements = svgContainer.selectAll("rect") 
        .data(series).enter().append("rect")
        .attr("x", function(d, i){
             return xPosLoop[i];
            })
        .attr("height", function(d,i){
             return elementHeight[i];
            })
        .attr("y", function(d, i){
             return yPosLoop[i];
            })
        .attr("width", function(d,i){
             return elementWidth[i];
           })
        .attr("rx", 7)
        .attr("fill", function(d, i){
             return color[i];
            })
        .addEventListener('click', rect_click)
        .attr("stroke", "#006ec5")
        .attr("stroke-width", 1);
 function rect_click(event)
                    {
                        console.log('I was clicked');
                    } 

您正在使用d3选择,而不是DOM元素本身。 要将事件侦听器分配给选择的元素,您可以执行以下操作:

.on('click', clickHandler)

将当前数据和元素索引传递给clickHandler 要访问事件,请使用d3.event

function clickHandler(d, i) {
    // d is the datum
    // i is the index
    // this is the reference to the current element
    // d3.event is the reference to the current event
}

请参阅selection.on(type[, listener[, capture]])文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM