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

时间:2012-09-22 19:52:52

标签: javascript jquery dom svg dom-manipulation

在树的中间插入节点的最佳建议/有效方法是什么。

如何转置此

<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);

我也尝试在this回答

中使用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的解决方案。

2 个答案:

答案 0 :(得分:4)

我建议:

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

JS Fiddle demo

参考文献:

答案 1 :(得分:0)

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

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