2015-10-02 85 views
3

我已經創建了具有一定價值的文本節點。所以無論何時數據更新,只有值應該更新,不應該再次創建文本節點。D3如何更新文字?

systemLevel 
.enter() 
.append('g') 
.classed("system-level", true) 
.attr("depth", function(d, i) { 
    return i; 
}) 
.each(function(d, i) { 
    var columnHeader = graphHeaders.append("g") 
           .classed("system-column-header", true); 
    columnHeader.append('text') 
       .attr('font-size', '14') 
       .attr('font-weight', 'bold') 
       .attr('fill', "red") 
       .attr('x', 50 * i) 
       .attr('y', 50) 
       .text(function() { 
       return d.newUser; 
       }); 
    columnHeader.append('text') 
       .attr('font-size', '14') 
       .attr('font-weight', 'bold') 
       .attr('fill', "blue") 
       .attr('x', 50* i) 
       .attr('y', 70) 
       .text(function() { 
       return d.value; 
       }); 
}); 

我在Js Bin上創建了一個示例。 https://jsbin.com/dixeqe/edit?js,output

我不確定如何更新文本值。任何幫助表示讚賞!

+0

那究竟是什麼問題呢? D3更新模式在許多教程中都有介紹,例如http://bost.ocks.org/mike/circles/ –

+0

我已經提到了很多關於更新的教程,但仍然無法在這個特定場景中使用它。 – user2532865

回答

2

您沒有使用通常的D3更新模式,在許多教程中都有介紹(例如here)。您需要重組的代碼無條件地使用,而不是追加新要素:

var columnHeader = graphHeaders.selectAll("g").data(dataset); 
columnHeader.enter().append("g").classed("system-column-header", true); 
var texts = columnHeader.selectAll("text").data(function(d) { return [d.newUser, d.value]; }); 
texts.enter().append("text") 
    .attr('font-size', '14') 
    .attr('font-weight', 'bold') 
    .attr('fill', "red") 
    .attr('x', function(d, i, j) { return 50 * j; }) 
    .attr('y', function(d, i) { return 50 + 20 * i; }); 
texts.text(function(d) { return d; }); 

修改jsbin here

+0

非常感謝Lars,作品完美。另一個問題 - 如果我們需要不同文本節點的不同屬性會怎樣? – user2532865

+1

製作這些數據的一部分並相應設置,例如'.attr(「font-size」,function(d){return d.fontSize;})'。 –