- 选择元素
- select() 返回选择元素的第一个
selectAll() 返回所有满足条件的元素
两者返回的结果都是选择集
数据绑定
D3.js非常便利的一个功能,将网页元素如<p>
和一个特定的数据如5
进行绑定。
D3中绑定数据有两个函数datum()
将一个数据绑定到选择集上
<html>
<head>
<meta charset="utf-8">
<title>hello world</title>
</head>
<body>
<p>hello world 1</p>
<p>hollo world 2</p>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var str = "china"
var p = d3.select("body").selectAll("p");
p.datum(str);
p.text(function (d, i) {
return "第 " + i + " 个元素绑定的数据是 " + d;
});
</script>
</body>
</html>
代码使用了匿名函数,当选择集需要使用绑定的数据时,常这么使用
d:代表选择集绑定的数据
i:代表数据的索引号
- data()
将一个数据绑定到选择集,数据中的元素分别与选择集中的元素绑定
<html>
<head>
<meta charset="utf-8">
<title>hello world</title>
</head>
<body>
<p>hello world 1</p>
<p>hollo world 2</p>
<p>hello world 3</p>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var dataset = ["I like dog", "I like cat", "I Like snakes"];
var p = d3.select("body").selectAll("p");
p.data(dataset);
p.text(function (d, i) {
return d;
});
</script>
</body>
</html>
*这段代码也用到了一个无名函数 function(d, i),其对应的情况如下:
*当 i == 0 时, d 为 I like dogs。
当 i == 1 时, d 为 I like cats。
当 i == 2 时, d 为 I like snakes。*