如何在我们的html页面中添加来自jquery的svg标签

How to append svg tag from jquery in our html page?

本文关键字:添加 jquery 标签 svg 我们 html      更新时间:2023-09-26

我想附加一些svg标记,然后在svg标记内,我想附加圆和线,我从XML文件中获取它们的坐标。

我可以从jquery.append中附加相同的标记,但我在浏览器中看不到任何东西,尽管标记是动态附加在DOM中的,但在浏览器中无法看到。

这是我的代码,用于从XML中获取数据并将其附加到DOM:-

$(xml).find("Quadron").children().each(function(i){
    var valueParameter=$(this).attr("value");
    var riskParameter=$(this).attr("risk");
    $('<circle/>',{
        clicked:'plot'+i,
        technology:$(this).parent().parent().attr("YearName"),
        quadronName:$(this).parent().attr("title"),
        class:'plot',
        cx:dotsXposition,
        cy:dotsYposition,
        r:function(){
            if(valueParameter=="high"){return 10;}
            else if(valueParameter=="medium"){return 5;}
            else if(valueParameter=="low"){return 2;}
            },
        fill:function(){
            if(riskParameter=="high"){return "#b42a2d";}
            else if(riskParameter=="medium"){return "#ebd62e";}
            else if(riskParameter=="low"){return "#72aa2c";}
            }
    }).appendTo('#circlePlot');
    $('<text/>',{
        clicked:'plot'+i,
        technology:$(this).parent().parent().attr("YearName"),
        class:'plot',
        text:$(this).text(),
        x:dotsXposition+15,
        y:dotsYposition
    }).appendTo('#circlePlot');
    dotsXposition+=10;
    dotsYposition+=10;
    });
}

我找到了以下代码,以便刷新页面并显示svg elemnts:-$("body").html($("body").html());

但是在我的java脚本文件中包含了这些代码之后,点击事件就不起作用了。

有什么办法解决这个问题吗。

您的问题似乎与html与svg命名空间有关。以下答案很好地总结了您的问题:jquery的append不能使用svg元素?

我的建议是使用js库来处理元素的创建。Snap svg是一个很好的解决方案,应该可以处理您遇到的问题。

此外,做$('body').html($('body').html());是一个非常糟糕的主意。从本质上讲,您正在擦除所有DOM元素(将所有事件绑定到它们),并使用全新的元素重建整个页面。这就是为什么你所有的活动都被破坏了。

得到了我问题的答案。我已经使用D3.js将SVG元素动态地附加到我的DOM中,现在它工作得很好。

我使用了以下代码:

d3.select("#circlePlot").append("circle")
            .attr("clicked","plot"+i)
            .attr("technology",$(this).parent().parent().attr("YearName"))
            .attr("quadronName",$(this).parent().attr("title"))
            .attr("class","plot")
            .attr("cx",500+(r*Math.cos(angle)))
            .attr("cy",350-(r*Math.sin(angle)))
            .attr("r",function(){
                if(valueParameter=="high"){return 10;}
                else if(valueParameter=="medium"){return 6;}
                else if(valueParameter=="low"){return 3;}
                })
            .attr("fill",function(){
                if(riskParameter=="high"){return "#b42a2d";}
                else if(riskParameter=="medium"){return "#ebd62e";}
                else if(riskParameter=="low"){return "#72aa2c";}
                });
        d3.select("#circlePlot").append("text")
            .attr("clicked","plot"+i)
            .attr("technology",$(this).parent().parent().attr("YearName"))
            .attr("class","plot")
            .text($(this).text())
            .attr("x",500+(r*Math.cos(angle))+10)
            .attr("y",350-(r*Math.sin(angle)));