D3.js如何選擇上一階元素(Panent Node)

先來看下列 d3.js 的程式碼,我要產生兩個不同大小、顏色的圓形

svg_test03 = d3.select("#svg_test03")
svg_test03_g = svg_test03.append('g')

svg_test03_g
  .append('circle')
  .attr('cx', 80 )
  .attr('cy', 60)
  .attr('r', 50)
  .attr('fill','#ff0000')
  .append('circle')
  .attr('cx', 80 )
  .attr('cy', 60)
  .attr('r', 40)
  .attr('fill','#ffffff')


其產生的svg碼如下,第二個圓被包在第一圓的程式碼之中,顯然這並不符合我們的需求,實際上第二個圓在網頁上也是沒有顯示出來




我們要的結果應該是兩個圓形都要在<g>元素底下才對。我們修改一下程式碼,讓第二個圓在新建時應該先取得上一階元素(<g>)

svg_test03_g
  .append('circle')
  .attr('cx', 80 )
  .attr('cy', 60)
  .attr('r', 50)
  .attr('fill','#ff0000')
  .select(function() { return this.parentNode; }) //取得上一階元素
  .append('circle')
  .attr('cx', 80 )
  .attr('cy', 60)
  .attr('r', 40)
  .attr('fill','#ffffff')


利用this.parentNode來取得上一階元素後再增加第二個圓,此時svg才會符合我們的期待,網頁上也才能正確顯示兩個圓形




如果要取得上二階的元素時,可以使用兩次的this.parentNode:

.select(function() { return this.parentNode; }) 
.select(function() { return this.parentNode; }) //利用兩次來取得上兩階的元素



Window 10利用PowerShell來關閉IPv6