官术网_书友最值得收藏!

Selections example

A big part of prototyping JavaScript code is playing around in the browser, using the JavaScript console to manipulate values. Instead of hitting refresh and logging the output a whole bunch, you can do things in the browser and instantly see the result. To do this, you attach functions to the window global object.

In main.js, replace all its contents with the following:

import tableFactory from './chapter2/table-factory'; 
import * as d3 from 'd3';

window.d3 = d3;
window.tableFactory = tableFactory;

This attaches the tableFactory function and D3 library to the global window object, so we can now use both freely in the console.
In Chrome's developer console, type the following two lines:

d3.selectAll('.table').remove(); 
tableFactory([
[1,2,3,4,5,6],
['q', 'w', 'e', 'r', 't', 'y'],
['a', 's', 'd', 'f', 'g', 'h'],
['z', 'x', 'c', 'v', 'b', 'n']
]);

Psst! If you need to add a newline character in Chrome's Developer console, hold shift while pressing return. Note that you don't actually need to do this; you can type the above all as one line if it's easier. I've only presented it this way for clarity.

This removes the old table (if you didn't refresh it in the meantime) and adds a new table.

Now, let's make the text in all of the table cells red:

d3.selectAll('td').style('color', 'red')

The text will promptly turn red. Now, let's make everything in the table head bold by chaining two d3.selectAll() calls:

d3.selectAll('thead').selectAll('th').style('font-weight', 'bold')

Great! Let's take nested selections a bit further and make table body cells green in the second, fourth, and sixth columns:

d3.selectAll('tbody tr').selectAll('td')
.style('color', (d, i) => { return i%2 ? 'green' : 'red'; })

The two d3.selectAll() calls gave us all the instances of <td> in the body, separated by rows, giving us an array of three NodeList objects with six elements each: [ NodeList[6]NodeList[6], and NodeList[6] ]. These are in the _groups array returned by d3.selectAll(), whereas the <tr> selections are stored in the _parents array. We then used .style() to change the color of every selected element.

Using a function instead of a static property gave us the fine-grained control we needed. The function is called with a datum argument (we'll discuss more on that later) and an index of the column it's in; that is, the i variable. Then, we simply return either green or red, based on the current index.
One thing to keep in mind is that chaining selections can be more efficient than OR selectors when it comes to very large documents. This is because each subsequent selection only searches through the elements matched previously.

主站蜘蛛池模板: 广元市| 巨野县| 齐河县| 芷江| 富蕴县| 桂阳县| 福建省| 城步| 长沙市| 苍梧县| 宝清县| 易门县| 昌平区| 天峻县| 赤城县| 阿坝县| 平利县| 米易县| 云林县| 昆山市| 绵阳市| 紫阳县| 万州区| 唐海县| 漯河市| 来宾市| 旺苍县| 美姑县| 山阳县| 乐昌市| 尖扎县| 南充市| 西峡县| 青冈县| 乌兰察布市| 夹江县| 石门县| 巴林左旗| 乌拉特后旗| 瓦房店市| 花莲市|