Then the previous one discussed how to select elements and use data.
Now there are three lines of text in the page, the code is:
[HTML]View PlainCopy
- <p>hello World 1</P>
- <p>hello World 2</P>
- <p>hello World 3</P>
Define a set set with three elements:
[HTML]View PlainCopy
- var set = [' I like dog ', ' I like cat ', ' I like Snake '];
To assign these three strings to the three <p> values above, the code is as follows:
[HTML]View PlainCopy
- var sp = d3.select ("Body"). SelectAll ("P"); Select element
- Sp.data (set)//working with data sets
- . text (function (d,i) {
- return D;
- });
The first line above indicates that all p in the body is selected, and the set is assigned to a variable p. The second line indicates that you want to use the data set set, and the third line indicates that you want to change the text content in P. Notice that there is a function (d,i) in the back, which is used to separate the elements in the set of data sets.
If the data collection set is not applicable, you want to change all the text to the same string (if it becomes China), just:
[HTML]View PlainCopy
- Sp.text ("China");
Can. If you want to use the set to assign a value, to use function functions (d,i), the function of the first parameter means datum (data), the second argument is index (index), it is important to note that when data function data is specified The set of data set and the P set you selected are one by one corresponding (if the number of sets and p is exactly the same, the case will be discussed later). The function has only one statement return D, which means that the data is returned directly, meaning that for each index I, data d is returned directly. D3.js will automatically assign values to each p in order of precedence.
Results such as:
What if we want to only select one of the elements to operate, assuming we want to manipulate only the Hello World 3?
There are two ways of doing this:
First, give a third p an ID, that is,
[HTML]View PlainCopy
- <p id="P3">hello World 3</P>
Then choose
[HTML]View PlainCopy
- var sp = d3.select ("Body"). Select ("#p3"); Select element
You can do it again.
Second, operate in function (D,i), for example
[HTML]View PlainCopy
- Sp.text (function (d,i) {
- if (i==2) {
- ....
- }
- });
From: Blog home: http://www.ourd3js.com/, csdn Blog home for: http://blog.csdn.net/lzhlzz/. Reprint please indicate the source, thank you.
"D3.js Starter Series---2" How to use data and select elements