d3.js入门-04赋值

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不匹配的元素,可以用来删除这些元素

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章