美文网首页d3(v5)
d3之绑定数据

d3之绑定数据

作者: 那头黑马 | 来源:发表于2019-08-16 18:11 被阅读0次

    d3全称是data driven documention 数据推动DOM,所以绑定数据是d3里面最最核心的部分。

    直接绑定数据

    首先p的内容只是简单的123,有这样一组数据,var dataset=[3,6,9,12,20] ,根据对应的数据生成对应的p。

    <div id="d1">
            <p>1</p>
            <p>2</p>
            <p>3</p>
            <p>1</p>
            <p>2</p>
            <p>3</p>
    </div>
    
    <script>
    var dataset=[3,6,9,12,20];
    var _p = d3.selectAll("p")
        .data(dataset)
        .text(function(d){return d});
    </script>
    
    p1.png

    exit()多余元素去除

    页面上共有6个元素,数组里只有5个p标签,所以只改变了前5个的内容。如果想要去掉最后一个标签,就需要用到另一个API--exit。以下为官方解释:

    # selection.exit() <>
    Returns the exit selection: existing DOM elements in the selection for which no new datum was found. (The exit selection is empty for selections not returned by selection.data.)

    _p.exit().remove("p");
    
    p2.png

    enter()只有数据,没有元素时,根据数据个数添加dom。

    与exit方法对应的是enter方法,也是最常用的方法,我们一般都是先拿到数据,然后根据数据个数append dom到页面上。enter方法官方解释:

    # selection.enter() <>
    Returns the enter selection: placeholder nodes for each datum that had no corresponding DOM element in the selection. (The enter selection is empty for selections not returned by selection.data.)

    上面括号里那句话很重要哦,enter方法上面的selection应该是空的!切记!!!
    所以我们没必要像上面那样绕弯子,直接enter()方法不就可以了。

    <div id="d1">
            <p>1</p>
            <p>2</p>
            <p>3</p>
            <p>1</p>
            <p>2</p>
            <p>3</p>
    </div>
    
    <script>
    var dataset=[3,6,9,12,20];
    var enters = d3.selectAll("#d1")
        .selectAll('.test')  //这里也可以换成页面上没有的类名,保证为空。
        .data(dataset) //绑定数据
        .enter() //因为以上选中的元素个数为0,但数组length不为0,故进入enter方法
        .append('p')
        .attr('class','test')
        .text(function(d){return d});
    </script>
    

    还有一个API也不容忽视,就是datum方法。

    以上我根据数据添加完p标签后,想获取绑定的数据,可以用此方法。

    d3.select('#d1')
         .selectAll('p')
         .datum(function(d){
                  if(d===12){
                            d3.select(this).style('color','red')
                        }
                    })
    
    p3.png

    不过不仅如此,它也可以重新绑定数据:

    # selection.datum([value]) <>

    Gets or sets the bound data for each selected element. Unlike selection.data, this method does not compute a join and does not affect indexes or the enter and exit selections.

    If a value is specified, sets the element’s bound data to the specified value on all selected elements. If the value is a constant, all elements are given the same datum; otherwise, if the value is a function, it is evaluated for each selected element, in order, being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). The function is then used to set each element’s new data. A null value will delete the bound data.

    If a value is not specified, returns the bound datum for the first (non-null) element in the selection. This is generally useful only if you know the selection contains exactly one element.

    This method is useful for accessing HTML5 custom data attributes. For example, given the following elements:

    <ul id="list">
      <li data-username="shawnbot">Shawn Allen</li>
      <li data-username="mbostock">Mike Bostock</li>
    </ul>
    

    You can expose the custom data attributes by setting each element’s data as the built-in dataset property.

    selection.datum(function() { return this.dataset; })
    

    主要阐述一下几点:
    1.datum可以获取以前绑定的数据(如果以前有绑定过),也可以绑定新的数据,无论以前有没有绑定过。
    2.用data绑定数据,只能是绑定数组。但是datum既可以绑定数组,也可以是数字,字符串。如果是常量,那所有的元素都会绑定同样的数据,如果是数组,就会根据索引,一一对应绑定,null,undefined无效。这时被绑定数据的元素就会多一个属性_data_,属性值就是绑定的数据。

    1. 那datum到底有啥子用?官网最后一句话让人眼前一亮,可以设置html的自定义属性。(这个工作中遇到了,绑定数据后,以后获取数据做各种判断太方便啦~~)
    var _p2 = d3.select('#d1')
                    .selectAll('p')
                    .datum(7)
                    .attr('data',function(d){
                        return d;
                    });
    console.log('ppp',_p.attr('data'));//获取属性用selection.attr('属性名');
    
    p4.png

    小结

    其实说了半天,无非就是 data(),exit(),enter(),datum()这四种方法,d3写多了就知道这几种方法太有用啦,除了exit用的少些。

    相关文章

      网友评论

        本文标题:d3之绑定数据

        本文链接:https://www.haomeiwen.com/subject/qvhqsctx.html