How can I add a tabindex attribute to an nvd3 pie

2019-09-16 23:31发布

问题:

I have a basic pie chart with 3 wedges. When you click on a wedge of the pie, a tooltip will display. My intent is to have the same functionality for a keydown event.

Scenario: When a pie slice has focus, a user can hit a key (ex: enter) which will display the tooltip exactly how the click event does.

I figured this will require 2 steps.

  1. Make each pie wedge (.nv-slice) focusable by adding a 'tabindex = 0' attribute
  2. Add an event listener that triggers the tooltip similar to how a click event does.

Here is the plunkr that shows the described behavior: http://plnkr.co/edit/7WkFK2LqzDyDmnIt2xlf?p=preview (thanks to @ThanasisGrammatopoulos)

First things first, how can I add a tabindex attribute to each pie wedge? When I try the following code it does not seem to appear:

d3.selectAll('.nv-slice').setAttribute("tabindex", "0");

Any ideas?

回答1:

So,

The function setAttribute is a vanila javascript, so it has to be used on a real javascript html element.

You have 2 options,

Solution 1

Get the javascript html element, using the function each and then getting it from this.

d3.selectAll('.nv-slice').each(function(){
    this.setAttribute("tabindex", "0");
});

Solution 2

Or as we know from jQuery (a vary polular library library) you can try to see if the equivalent function of the setAttribute exist, this function is attr.

d3.selectAll('.nv-slice').attr("tabindex", "0");

Of course all that inside the callback function.