使用 jQuery 在树 (SVG) 的中间插入一个 (g) 节点



树中间插入节点的最推荐/最有效的方法是什么?

如何转置此内容

<svg id="root" ... >
  <g id="child1">...</g>
  <text id="child2">...</text>
  <rect id="child3">...</rect>
  ...
</svg>

对此

<svg id="root" ... >
  <g id="parent">
    <g id="child1">...</g>
    <text id="child2">...</text>
    <rect id="child3">...</rect>
    ...
  </g>
</svg>

@jsFiddle

我试过了

var $parent = $("g").attr("id","parent");
var $root = $("#root");
$root.contents().each(function(){
   $child=$(this);
   $child.remove();
   $parent.append($child);
});
$root.append($parent);

我也尝试在此答案中使用 moveTo 方法

(function($){
    $.fn.moveTo = function(selector){
        return this.each(function(){
            var cl = $(this).clone();
            $(cl).appendTo(selector);
            $(this).remove();
        });
    };
})(jQuery);
$root.contents().each(function() {
    $(this).moveTo($parent);
});

所有这些方法都可以在简单的场景中工作,但是当树真的很大时,浏览器只是挂起,有没有更有效的方法来执行此操作?
我正在寻找jQuery或纯JavaScript解决方案。

我建议:

$('#root > div').wrapAll('<div id="parent" />');

JS小提琴演示。

引用:

  • wrapAll() .

这将只对 DOM 进行一次添加,因此这将很快:

$('#root').html('<div id=parent>'+$('#root').html()+'</div>');

最新更新