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

Manipulating content

We can do far more with D3 than just playing around with selections and changing the properties of the elements. We can change the properties of elements on the page.

With D3, we can change the contents of an element, add new elements, or remove elements we don't want.

Let's add a new column to the table from our preceding example:

const newCol = d3.selectAll('tr').append('td')

We selected all the table rows (which returned a new selection object) and then appended a new cell to each using the .append() selection. All D3 actions return the current selection, so we can chain actions or assign the new selection to a variable newCol  for later use.

We have an empty invisible column on our hands. Let's add some text to spruce things up:

newCol.text('a')

At least now that it's full of instances of a, we can say a column is present. However, that's kind of pointless, so let's follow the pattern set by other columns:

newCol.text((d, i) => ['Seven', 'u', 'j', 'm'][i])

The trick of dynamically defining the content via a function helps us pick the right string from a list of values depending on the column we're in, which we identify by the index i. Figured out the pattern, yet?

Similarly, we can remove elements using .remove(). For instance, to get rid of the last row in the table, you'd write something as follows:

d3.selectAll('tbody tr:last-child').remove()
主站蜘蛛池模板: 龙岩市| 中牟县| 库伦旗| 太谷县| 通渭县| 洪泽县| 阿勒泰市| 秭归县| 池州市| 石棉县| 阿尔山市| 宝丰县| 蒲江县| 黑龙江省| 璧山县| 泾源县| 竹山县| 龙里县| 聊城市| 湖北省| 于田县| 满洲里市| 通山县| 永寿县| 澎湖县| 遂溪县| 马龙县| 新乐市| 北票市| 永康市| 安溪县| 军事| 邻水| 青神县| 连云港市| 新沂市| 大兴区| 西充县| 五大连池市| 明光市| 治多县|