2016-06-21 64 views
1

每當我登錄selection.attributes時,它會記錄所需的值,例如,如果存在名爲y的屬性,它將記錄相同的值rect在運行時在DOM中有,但是每當我嘗試使用selection.attributes.y.nodeValue訪問該值時,它都會返回它所呈現的rect的原始值。d3 selection.attributes.key.nodevalue不返回當前DOM值

我的問題是,如果實際屬性對象具有當前值,那麼當我嘗試訪問該對象中的鍵(在此例中爲y.nodeValue)時,它爲什麼會返回不同的值?

對於進一步的解釋:

這裏是我的日誌對象和代碼代碼用於記錄值的檢索:

var notLiveYAttributes = chart.select("#not-live" + i + " rect.not-live")[0][0].attributes; 
       console.log(notLiveYAttributes); 
       console.log(notLiveYAttributes.y.value); 

輸出:

enter image description here

什麼時我在這裏錯過了,以及如何檢索屬性的當前值(y和h)八),而不是當它最初呈現/填充?

+0

你嘗試過不同的瀏覽器嗎? – Klaujesi

+0

這不是瀏覽器問題,我在這裏解釋了這個問題:http://stackoverflow.com/questions/37951771/d3-selection-attributes-key-nodevalue-doesnt-return-the-current-dom-values #comment63386583_37968197 –

回答

2

沒有看到你的代碼的其餘部分,我想說這裏的問題是你的var notLiveYAttributes被宣佈在你應用到元素的任何修改之前被初始化。因此,鑑於javascript的性質和JavaScript代碼的解析方式,瀏覽器會立即記錄notLiveYAttributes,其值可能與當前DOM值不匹配。

我提出這個簡單的小提琴說明這一點:https://jsfiddle.net/55ezeLef/1/

我其中y = 10。在一些rects然後,我由過渡,改變y以50

即使代碼到控制檯。記錄過渡後的y值,如下所示:

rects.transition().duration(1000) 
    .attr("y", 50); 

var notLiveYAttributes = svg.select(".rect2")[0][0].attributes.y.value; 
    console.log("the immediate value is " + notLiveYAttributes); 

它會記錄the immediate value is 10

但如果我等待一點點:

setTimeout(function(){ 
    var notLiveYAttributes = svg.select(".rect2")[0][0].attributes.y.value; 
     console.log("after waiting, the value is " + notLiveYAttributes); 
}, 1500); 

它將記錄after waiting, the value is 50

+1

這正是我正在做的,實際上我在應用轉換之前訪問了值,所以'notLiveYAttribiutes'記錄了轉換後應用的最終屬性,在訪問單個值時在當前時刻記錄了該值。非常感謝,非常感謝您的意見。 –