2013-10-25 31 views
1

在一個非常特殊的地方插入元素說我有以下的DOM結構:如何使用D3

div 
    > svg 
    > defs 
    > g 
     > rect 
     > g 
     > g 
      <-- I want to insert an element here 
     > g 
     > g 

無父g的孩子g元素有一個類,ID,或其他任何東西我的可以用作選擇器,我不能修改它們,因爲它們來自加載到頁面中的第三方小部件。

到目前爲止我能做的最好的插入到第三個g元素,但這是不可接受的。我想在父親g的孩子中添加第六個元素,在當前指數2和3之間(或者如果您不計算rect,則指數爲1和2)。

這是我迄今所做的:

var test = d3.selectAll('#continer svg > g > g'); 
test = d3.select(test[0][2]); 
test.append('foreignObject'). 
    attr('width', 690).attr('height', 500) 
    .append('xhtml:body').style('font', '14px "Helvetica Neue"') 
    .html('<h1>An HTML Foreign Object in SVG</h1>'); 

有了,我結束了以下結構:

div 
    > svg 
    > defs 
    > g 
     > rect 
     > g 
     > g 
     > g 
     > foreignobject & its children inserted here 
     > g 

...我明白爲什麼。我曾嘗試D3的insert方法使用函數作爲第二個參數指定before,但瀏覽器不斷告訴我:

試圖在它不存在 的上下文中引用Node。

回答

1

好,所以這個工程,但它有點破解。我使用jQuery在使用D3追加後重新排列元素。如果可能的話,仍然希望看到一個純D3解決方案:

// select the parent g element 
var parentG = d3.select('#continer svg > g'); 

// append a new G element with a nested foreign object 
parentG.append('g').attr('id', '__my_custom_id') 
    .append('foreignObject').attr('width', 690).attr('height', 500) 
    .append('xhtml:body').style('font', '14px "Helvetica Neue"') 
    .html('<h1>An HTML Foreign Object in SVG</h1>') 
; 

// now use jQuery to rearrange the order of the elements 
$('#__my_custom_id') 
    .insertAfter('#container svg > g > g:nth-child(3)') 
    .removeAttr('id') 
;