score:8

Accepted answer
for (var index in nodeValues) {
    var rect = svg.append("rect")
        .attr(elementAttr(index))
        .style("fill", "red" )
        .on('click', function(d,i) {
            // handle events here
            // d - datum
            // i - identifier or index
            // this - the `<rect>` that was clicked
        });
}

score:2

I gave a vote to Stephen's answer but it's actually just missing one part - instead of .click, it's

.on("click", function(d){...

Here's some documentation. Also, I've jacked Mike's example of zooming with circles in order to implement the binder listener. Here's a fiddle that shows it.

Hope that helps!

score:3

I've refactored your code to be more D3-like -- in particular, you don't need a loop if you use D3's selections and data matching. The code then looks like this:

svg.selectAll("rect")
    .data(nodeValues).enter().append("rect")
    .each(function(d) {
        var attrs = elementAttr(d);
        d3.select(this).attr(attrs);
    })
    .style("fill", rectColor);

Adding the click handler is just an additional statement at the end of this:

    .on("click", function() {
        d3.select(this).attr("width", 120);
    });

Complete demo here.


Related Query

More Query from same tag