使用jQuery在树中插入(g)节点(SVG) [英] Inserting a (g) node in the middle of a tree (SVG) using jQuery

查看:128
本文介绍了使用jQuery在树中插入(g)节点(SVG)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如何处理这个

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



我尝试过

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

我还尝试在这个答案

 (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/>'); 



参考文献:




What is the most recommended/efficient way to insert a node in the middle of a tree.

How to transpose this

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

to this

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

@jsFiddle

I have tried

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

I have also tried using the moveTo method in this answer

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

All of these methods work in simple scenarios but when the tree is really massive, the browser simply hangs, is there a more efficient way to perform this?
I am looking for a jQuery or pure javascript solution.

解决方案

I'd suggest:

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

JS Fiddle demo.

References:

这篇关于使用jQuery在树中插入(g)节点(SVG)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆