d3 - Selections 和 Data Join

2022-10-12  本文已影响0人  戊戌水瓶

Selections

select() - 通过匹配给定的CSS选择器,仅选择一个DOM元素。 如果给定的CSS选择器有多个元素,则仅选择第一个元素。

selectAll() - 通过匹配给定的CSS选择器来选择所有DOM元素。 如果您熟悉使用jQuery选择元素,则D3.js选择器几乎相同。

1、The select() method

    d3.select(“div”)        //  按标签选择

    d3.select(“.<classname>”)    // 按类名选择

    d3.select(“#<id of an element>”)   //    按ID选择

2、添加DOM元素

    append()方法在div标签内添加一个新标签span

    text()方法用于设置所选/附加元素的内容

    d3.select("div.myclass").append("span").text("from D3.js");

3、修改元素

    html()方法用于设置所选/附加元素的html内容。

    d3.select(".myclass").html("Hello World! <span>from D3.js</span>");

    attr()方法用于添加或更新所选元素的属性。 

    d3.select(".myclass").attr("style", "color: red");  = .style("color", "red");

3、The classed() Method

        Add class - 要添加类,必须将分类方法的第二个参数设置为true,删除需要设置为false

    d3.select(".myclass").classed("myanotherclass", true);

    d3.select(".myclass").classed("myanotherclass", false);

    要检查是否存在类,只需省略第二个参数并传递要查询的类名。 如果存在则返回true,否则返回false。

    d3.select(".myclass").classed("myanotherclass");

Data Join

数据连接的主要目的是使用给定的数据集映射现有文档的元素。 

1、data()

<ul id = "list">

  <li></li>

  <li></li>

</ul>

    给前两个元素赋值

d3.select("#list").selectAll("li")

  .data([10, 20, 30, 25, 15])

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

给所有的数据都显示 - enter()方法提供对 剩余数据(未映射到现有元素)的访问

d3.select("#list").selectAll("li")

  .data([10, 20, 30, 25, 15])

  .text(function(d) { return "This is pre-existing element and the value is " + d; })

  .enter()

  .append("li")

  .text(function(d)

      { return "This is dynamically created element and the value is " + d; });

    参数“d”提供数据元素,“i”提供数组中的数据索引

        var data = [1, 2, 3];

        var paragraph = d3.select("body")

        .selectAll("p")

        .data(data)

        .text(function(d, i){

            console.log("d: " + d);

            console.log("i: " + i);

            console.log("this: " + this);

            return "The index is " + i + " and the data is " + d;

        });

2、datum()

    方法用于为HTML文档中的单个元素设置值。 

    d3.select("p")

      .datum(50)

      .text(function(d) {

        return "Used existing paragraph element and the data " + d + " is assigned.";

      });

上一篇下一篇

猜你喜欢

热点阅读