If you are interested in D3.js or data visualization, welcome to www.ourd3js.com for discussion.
Next I will discuss how to select elements and use data.
The page now contains three lines of text with the code:
Hello World 1
Hello World 2
Hello World 3
Defines a set with three elements:
var set = ["I like dog","I like cat","I like snake"];
Use these three strings to give the preceding three strings respectively.
The Code is as follows:
Var sp = d3.select ("body "). selectAll ("p"); // select the sp element. data (set) // use a data set. text (function (d, I) {return d ;});
The first line above indicates Selecting All p in the body, and then assigning this set to a variable p. The second line indicates that the data set is to be used, and the third line indicates that the text content in p is to be changed. Note that there is a function funciont (d, I) to use the elements in the data set separately.
If the data set is not applicable, you only need:
sp.text("China");
You can. If you want to assign values by using a set, you need to use the function (d, I). The first parameter of this function means datum (data ), the second parameter indicates index. Note that when data is specified by the data function, the data set corresponds to the selected p set one by one (if the number of set and p is exactly the same, we will discuss it later ). There is only one statement in the function, return d;, which indicates that data is directly returned for each index I. D3.js automatically assigns values to each p in sequence.
The result is as follows:
If we want to select only one of the elements for the operation, assuming we only want to operate Hello World 3, what should we do?
There are two methods:
1. assign an id for the third p, that is
Hello World 3
Then select
Var sp = d3.select ("body"). select ("# p3"); // select an element
Then perform the operation.
2. Operate in function (d, I), such
sp.text(function(d,i){if(i==2){ ....}});