Dom 如何使用D3在非常特定的位置插入元素

Dom 如何使用D3在非常特定的位置插入元素,dom,svg,d3.js,Dom,Svg,D3.js,假设我有以下DOM结构: div > svg > defs > g > rect > g > g <-- I want to insert an element here > g > g div > svg > defs > g > rect > g >

假设我有以下DOM结构:

div
  > svg
    > defs
    > g
      > rect
      > g
      > g
          <-- I want to insert an element here
      > g
      > g
div
  > svg
    > defs
    > g
      > rect
      > g
      > g
      > g
        > foreignobject & its children inserted here
      > g
因此,我最终得到以下结构:

div
  > svg
    > defs
    > g
      > rect
      > g
      > g
          <-- I want to insert an element here
      > g
      > g
div
  > svg
    > defs
    > g
      > rect
      > g
      > g
      > g
        > foreignobject & its children inserted here
      > g
。。。我明白为什么。我尝试了D3的
insert
方法,使用一个函数作为第二个参数,在
之前指定
,但浏览器一直告诉我:

试图引用上下文中不存在的节点 存在


好的,这是可行的,但有点像黑客。在使用D3追加元素之后,我使用jQuery重新排列元素。如果可能的话,我仍然希望看到纯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')
;
//选择父g元素
var parentG=d3。选择(“#continer svg>g”);
//用嵌套的外部对象追加新的G元素
parentG.append('g').attr('id','u我的\自定义\ id'))
.append('foreignObject').attr('width',690)。attr('height',500)
.append('xhtml:body').style('font','14px“Helvetica Neue'))
.html(“SVG中的html外部对象”)
;
//现在使用jQuery重新排列元素的顺序
$(“#uu我的u自定义u id”)
.insertAfter(“#容器svg>g>g:n子级(3)”)
.removeAttr('id'))
;

好的,这样做是可行的,但有点做作。在使用D3追加元素之后,我使用jQuery重新排列元素。如果可能的话,我仍然希望看到纯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')
;
//选择父g元素
var parentG=d3。选择(“#continer svg>g”);
//用嵌套的外部对象追加新的G元素
parentG.append('g').attr('id','u我的\自定义\ id'))
.append('foreignObject').attr('width',690)。attr('height',500)
.append('xhtml:body').style('font','14px“Helvetica Neue'))
.html(“SVG中的html外部对象”)
;
//现在使用jQuery重新排列元素的顺序
$(“#uu我的u自定义u id”)
.insertAfter(“#容器svg>g>g:n子级(3)”)
.removeAttr('id'))
;