简体   繁体   中英

SVG rectangle click eventlistener

I have plotted svg rectangles in the following manner and I am trying to add a click event to it in the following way.But, the code is not working. Where am I going wrong?

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

You're working with d3 selections, not the DOM elements themselves. To assign an event listener to the elements of the selection you can do:

.on('click', clickHandler)

The clickHandler is passed the current datum and the element index. To access the event, use 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
}

See selection.on(type[, listener[, capture]]) documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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