【问题标题】:Why selection update not working when I pass them into another function?当我将它们传递给另一个函数时,为什么选择更新不起作用?
【发布时间】:2016-10-17 10:15:52
【问题描述】:

我想重复使用选择。 但更新方法不起作用。 为什么会这样?

第一个选择是否不能连续接受两个以上的数据绑定?

// 1. prepair data
var enterData = [120, 70, 300, 80, 220];
var updateData = [300, 0, 30, 70, 320];
var exitData = [300, 80, 90, 40];

// 2. select virtual element and assign it variable
var rects = d3.select("#myGraph")
    .selectAll("rect");

// 3. enter method working.
function enter (rects, data){
  console.log("enter method!");
  rects.data(data)  
  .enter()  
    .append("rect") 
    .attr("class", "bar")   
    .attr("width", function(d,i){   
    return d;   
  })
    .attr("height", 20) 
    .attr("x", 0)   
    .attr("y", function(d, i){  
    return i * 25   
  })
}

// 4. but update not working    
function update (rects, data){
  console.log("update method!");

  // 5. without below selection phrase
    // var rects = d3.select("#myGraph")
  //  .selectAll("rect");

  rects.data(data)
    .attr("width", function(d,i){   
    return d;
  })
}

function exit (rects, data){
    console.log("exit method!");
    rects.data(data).exit().remove();
}

setTimeout( function(){
  enter(rects ,enterData)
}, 1500 )

setTimeout( function(){
  update(rects, updateData)
}, 3000 )

setTimeout( function(){
  exit(rects, exitData)
}, 4500 )

我知道如何解决它。但我不知道为什么。

https://jsfiddle.net/baram204/Lteby67L/6/

【问题讨论】:

    标签: d3.js recycle selectall


    【解决方案1】:

    原因是 最初当你这样做时:

    var rects = d3.select("#myGraph")
        .selectAll("rect");
    

    #myGraph div 中没有rect DOM 元素,因此选择为空。

    在 enter 函数中,由于选择为空,我们为数据创建尽可能多的 DOM 并将数据绑定到 DOM。

    现在在update/exit 函数中,您传递了相同的空选择。 所以不会发生更新/退出。

    正确的做法是:

    function update (rects, data){
      console.log("update method!", rects);
    
      // 5. re-select your data
         var rects = d3.select("#myGraph")
       .selectAll("rect");
    
      rects.data(data)
        .attr("width", function(d,i){   
            console.log(d)
        return d;
      })
    }
    

    工作代码here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-23
      • 2019-06-29
      • 2015-11-30
      • 1970-01-01
      • 2021-05-29
      相关资源
      最近更新 更多