d3提供了爲元素賦值的方法:datum(),data(), enter(),exit()
datum() :是給單個元素賦值,與select()連用
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<div>111</div>
<script>
d3.select("div")
.datum("aaaa")
.text(function(d) {
return "Created new paragraph element and the data " + d + " is assigned.";
});
</script>
</body>
</html>
data():是給多個元素賦值,與selectAll()連用
<html>
<head>
<script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<p></p>
<p></p>
<div></div>
<script>
d3.selectAll("p")
.data(["aaa","bbbb"])
.text(function(d) {
return "Created new paragraph element and the data " + d + " is assigned.";
});
</script>
</body>
</html>
enter():當data 設置的數值與選擇的元素不匹配(設置的數值多)的情況 將多出的數值預設置在其中,後邊用appden去添加相應的元素,來展示 也是與data,selectAll連用(該方法是給超出的預設元素賦值,不超出的是不會設置值的)
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<ul id="list">
</ul>
<script>
d3.select("#list").selectAll("li")
.data([2,3,4])
.enter()
.append("li")
.text(function(d) { return "This is dynamically created element and the value is " + d; });
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<ul id="list">
<li>111</li>
<li>222</li>
<li></li>
<li></li>
</ul>
<script>
d3.select("#list").selectAll("li")
.data([2,3,4,2,3,1])
.enter()
.append("li")
.text(function(d) { return "This is dynamically created element and the value is " + d; });
</script>
</body>
</html>
輸出值爲
- 111
- 222
- This is dynamically created element and the value is 3
- This is dynamically created element and the value is 1
exit():返回與data不匹配的元素,可以用來刪除這些元素