问题描述:

I have a chart with a click event, it works well until I click on the label (group/fixed labels). After this the event doesn't work anymore.

I've attached this event to my page:

d3.selectAll("rect.nv-bar").on("click", function (d) {

alert("Clicked");

});

Here's a fiddle with the problem:

http://jsfiddle.net/ygQZW/

Am I doing something wrong or it's some kind of bug?

-- UPDATE --

The solution that @explunit posted solved 50% of my problem. Now, when I click on the color labels for hide/show the bars, the click effect stops on the bar previously hidden.

Here's the updated fiddle: http://jsfiddle.net/ygQZW/1/

How can I fix this?

网友答案:

If you namespace your click handler then it will not be overwritten by whatever else NVD3 is doing with events as the graph changes:

d3.selectAll("rect.nv-bar").on("click.mine", function (d) {
    alert("Clicked");
});

From the API:

To register multiple listeners for the same event type, the type may be followed by an optional namespace, such as "click.foo" and "click.bar".

网友答案:

I solved this problem by myself.

Instead of using d3.selectall I used the jQuery selector and I've selected the parent tag. In the parent tag I've attached a hover event which start another one on the children nodes.

By doing this, when the bars are hidden and then showed again, the parent tag event start the click events again.

My new code:

$(".nv-group").on("hover", function(d) {
    $(".nv-bar").off("click"); // Remove previous events, if have
    $(".nv-bar").on("click", function(d) {
        alert("Clicked!");
    });
});

Updated jsFiddle: http://jsfiddle.net/ygQZW/4/

I think that this isn't the best and graceful solution, if someone have a better solution please post it!

相关阅读:
Top