【问题标题】:Inserting a (g) node in the middle of a tree (SVG) using jQuery使用 jQuery 在树 (SVG) 中间插入 (g) 节点
【发布时间】:2012-09-14 20:38:17
【问题描述】:

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

如何转置这个

<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 解决方案。

【问题讨论】:

    标签: javascript jquery dom svg dom-manipulation


    【解决方案1】:

    我建议:

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

    JS Fiddle demo.

    参考资料:

    【讨论】:

    • 感谢您的快速回答,我不知道 wrapAll() 方法。它可以非常有效地操作 DOM,但是我要包装的新元素是 g 元素,并且在操作后图形不会显示 [jsfiddle.net/jugal/mxc2x/2/]。如果我手动(使用萤火虫)编辑html以将svg元素的子元素包裹在g元素周围一切正常,我会假设通过javascript完成时也会发生同样的情况? g 正确显示在 svg 内,所有子项都已移动,但在 firebug 中显示为灰色(如隐藏元素)
    • 愚蠢的我,$("#parent").show(); 成功了,但知道为什么它最初是隐藏的吗?
    • 我真的不知道;但主要是因为我不想涉足你的演示。嗯,对不起...我知道,这听起来很糟糕... =(
    • 没问题,我能理解 :) 无论如何它不是 OP 的一部分,可能我手头有一个新问题 ;)
    【解决方案2】:

    这只会在 DOM 中添加一个,因此速度会很快:

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

    【讨论】:

    • 您在$('#root').html 之后忘记了括号,这很可能会破坏绑定到这些元素的所有侦听器和数据。
    • 感谢您的快速响应,我还添加了一个 jsFiddle 示例,它是我试图操作的 svg 元素。让我试试你的建议,直到你看看小提琴
    猜你喜欢
    • 2021-09-03
    • 2020-09-29
    • 1970-01-01
    • 2012-01-08
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 2019-12-13
    相关资源
    最近更新 更多