簡體   English   中英

D3嘗試訪問json對象中的vis元素

[英]D3 trying to access vis element in json object

我正在嘗試使用D3訪問下面的json對象中的vis元素(請參見屏幕截圖),但無法這樣做。 使用類似於以下內容的代碼,我可以毫無問題地訪問鍵和值元素:

console.log(d.key);

但這不起作用(我收到未定義的錯誤):

console.log(d.vis);

有什么想法我做錯了嗎? 謝謝!

json obj

以下是一些代碼段:

var nested = d3.nest().key(function(d) { return d._id.stream; })
  .entries(data.result);

var stream = main.selectAll(".stream")
  .data(nested)
  .enter().append("g")
  .attr("class", "stream");    

  stream.append("rect")
  .attr("height",10)
  .attr("width", 25)
  .attr("x",width-215)
  .attr("y", function(d,i) { return height-400 + (i*40); })
  .attr("stroke", function(d) { return color(d.key);})
  .attr("fill",function(d) {
      if(d.vis=="1") {
        return color(d.key);
      }
      else {
        return "white";
      }
   })
   .on("click", function(d) {
     console.log(d);
     console.log(d.vis);  // undefined
     if(d.vis=="1") {
        d.vis="0";
      }
      else{
        d.vis="1";
      }
   });

看起來正在發生以下情況。 點擊處理程序功能被執行。 在內部,您正在記錄d.vis ,它是未定義的。 之后的代碼將檢查d.vis是否具有特定值,否則將其設置為“ 1”。 該“其他”包括未定義的情況。

因此,在執行處理程序之后, d.vis所有d設置d.vis 您正在使用的調試器顯示變量的值,該值console.log()語句之后進行了修改 也就是說,在您打印dd.vis確實未定義。 但是您要在之后立即進行設置,這就是您在控制台中看到的內容。

日志在打印時不會d.vis變量狀態的快照,但會向您顯示當前版本(在本例中已設置d.vis

注意數據結構:請參閱fetchData.js,除了priceList和name之外,還應該有vis元素,用於確定是否顯示曲線。

//The main data array of the graph
//format:
//data2 (List of fundObj)
//   fundObj (Name, priceList)
//      Name
//      vis
//      priceList (List of priceItem)
//         priceItem (date, price)

因此,請清楚代碼中的“ d”是什么,這完全取決於您傳遞給調用的數據:

var fund = focus.selectAll(".fund")
        .data(data2)
        .enter().append("g")
        .attr("class", "fund");

這里的data2是原始數據,您可以使用其他結構,但是需要在“ d”處修改一些代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM