D3——动态绑定数据

一、绑定数组元素

var dataset = [5, 10, 15, 20, 25 ];

d3.select("body")
    .selectAll("p")    
    .data(dataset)  
    .enter()
    .append("p")
    .text("New paragraph!");

d3.select("body"):选择body

.selectAll("p"): 选择body中的所有p元素,此时还没有创建p元素, 因此this returns an empty selection.

.data(dataset): 统计并分析数据元素,dataset中有5个元素,因此之后的每步操作都重复执行5次

.enter():如果数据值的个数大于对应的DOM元素的个数,enter()将为没有对应DOM元素的值创建占位符

.append("p"):

.text("New paragraph!"):

.text(function(d) {return d;});

.text(function(d) {
    return "I can count up to " + d;
});

.style("color", "red");

.style("color", function(d) {
    if (d > 15) {   //Threshold of 15
        return "red";
    } else {
        return "black";
    }
});

原文地址:https://www.cnblogs.com/xuepei/p/7526769.html