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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值