2017-06-15 57 views
2

我有一個用於顯示時間軸的庫。根據您輸入庫中的數據,如果數據包含特定值,我希望顯示元素或不顯示元素。d3如果數據中存在值,則添加文本元素

實施例而不number值:

var labelColorTestData = [ 
    {label: "person a", times: [{"color":"green", "label":"Weeee", "starting_time": 1355752800000, "ending_time": 1355759900000}, {"color":"blue", "label":"Weeee", "starting_time": 1355767900000, "ending_time": 1355774400000}]}, 
    {label: "person b", times: [{"color":"pink", "label":"Weeee", "starting_time": 1355759910000, "ending_time": 1355761900000}, ]}, 
    {label: "person c", times: [{"color":"yellow", "label":"Weeee", "starting_time": 1355761910000, "ending_time": 1355763910000}]} 
    ]; 

實施例與number值:

var testData = [ 
      {times:[ 
       {"id": "day1", "label": "DAY", "number": "1", "starting_time": 1, "ending_time": 86400}, 
       {"id": "day2", "label": "DAY", "number": "2", "starting_time": 86400, "ending_time": 86400*2}, 
       {"id": "day3", "label": "DAY", "number": "3", "starting_time": 86400*2, "ending_time": 86400*3}, 
       {"id": "day4", "label": "DAY", "number": "4", "starting_time": 86400*3, "ending_time": 86400*4}, 
       {"id": "day5", "label": "DAY", "number": "5", "starting_time": 86400*4, "ending_time": 86400*5} 
      ]}, 
    ]; 

我想如果number變量存在添加一個文本元素。以下代碼總是添加一個文本元素。

g.selectAll("svg").data(data).enter() 
         .append("text") 
         .attr("class", "textnumbers") 
         .attr("id", (d) => (d.id)) 
         .attr("x", (d, i) => getXTextPos(d, i, d.number, '.textnumbers')) 
         .attr("y", getStackTextPosition) 
         .text(function(d) { 
          return d.number; 
         }) 
         .on("click", function(d, i){ 
          // when clicking on the label, call the click for the rectangle with the same id 
          var point = d3.mouse(this); 
          var id = this.id; 
          var selectedLabel = d3.select(this).node(); 
          var selector = "rect#" + id; 
          var selectedRect = d3.select(selector).node(); 
          click(d, index, datum, selectedLabel, selectedRect, xScale.invert(point[0])); 
         }) 
        ; 

如何添加文本元素,如果number是存在於起始數據,如果不是呢?

謝謝!

回答

2

data(data).enter()粘貼此行

.filter(function(d) { return d.number !== undefined; })

相關問題