2016-05-20 22 views
-2

我已經創建了d3強制佈局,並且工作得很好。 我的主要代碼如下所示:兒童元素沒有繼承D3強制佈局的父數據

var nodes = [{id:1, n:'n_1',np:'0'},{id:2, n:'n_2',np:'0'}];//just for demo 
//1. set data 
var update = svg.selectAll(".node").data(nodes); 
//2. enter 
update.enter().append("svg:g").attr("class", "node") 
.call(function(p){ 
    p.append("svg:image").attr("class", "nodeimage"); 
    p.append("svg:text").attr("class", "nodetext"); 
}); 
//3. exit 
update.exit().remove(); 

正如我們所知,d3.selectAll( 「節點」)數據()是我的數據。因爲g的子元素會繼承父數據中的數據,所以d3.selectAll(".nodeimage").data()也是我的數據。對了?

事實上,我的數據節點來自後端,並且數據被更新。例如,某些屬性如np已從0更改爲1.我們認爲結果爲 nodes = [{id:1, n:'n_1',np:'1'},{id:2, n:'n_2',np:'0'}];

我需要再次調用上面的函數。但是,d3.selectAll(".node").data()是正確的,而d3.selectAll(".nodeimage").data()現在是錯誤的。

以下代碼無法正常工作。

d3.selectAll('.nodeimage').attr("test", function(d){ 
    //d.np is a wrong value. 
}); 

對我有何建議?

這裏是我的jsfiddle的演示:http://jsfiddle.net/bpKG4/663/

+5

,什麼是你的問題? –

+0

必須有別的東西在你的代碼中編輯'np'的地方。你可以發佈代碼來顯示錯誤的完整示例嗎? – tarulen

+0

@tarulen我親愛的朋友,我已經完成了我的演示jsfiddle.Please看看它,我需要你的幫助,謝謝。 – Does

回答

0

這是d3一個奇怪的行爲。如果我理解正確(未授予),selection.data(...)會自動將數據傳輸到子元素,除非它們已經綁定了一些數據。

在你的情況,這意味着你需要「手動」將數據複製到每個孩子:

//select any child node, then: 
    .each(function() { 
     d3.select(this).datum(d3.select(this.parentNode).datum()); 
    }) 

注意:在你的小提琴,你只設置xlink:hrefenter()的選擇:這是錯誤,您需要在整個update選擇範圍內進行設置。

update.selectAll(".nodeimage") 
      .each(function() { 
      d3.select(this).datum(d3.select(this.parentNode).datum()); 
      }) 
      .attr("xlink:href", function(d){ 
      var img; 
      if(d.np == 1){ 
       img = "http://www.gravatar.com/avatar/1eccef322f0beef11e0e47ed7963189b/?default=&s=80" 
      }else{ 
       img = "http://www.gravatar.com/avatar/a1338368fe0b4f3d301398a79c171987/?default=&s=80"; 
      } 
      return img; 
      }); 

在這裏看到:http://jsfiddle.net/cs4xhs7s/1/

+0

@ user1613381有幫助嗎? – tarulen

+0

是的,非常感謝你,它工作得很好。 – Does

+0

@Does然後隨意接受答案;) – tarulen