在SVG中添加新行,但是线条无法显示的错误

14

我想在SVG中添加一条新线。 当按下“添加”按钮时,应该向SVG中添加一条新线。 我确认已将该线添加到元素中,但为什么没有显示在屏幕上?

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#map
{
    border:1px solid #000;
}
line
{
    stroke:rgb(0,0,0);
    stroke-width:3;
}
</style>
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
    $("#add").click(function(){
        var newLine=$('<line id="line2" x1="0" y1="0" x2="300" y2="300" />');
        $("#map").append(newLine);
    });
})
</script>
</head>

<body>

<h2 id="status">
0, 0
</h2>
<svg id="map" width="800" height="600" version="1.1" xmlns="http://www.w3.org/2000/svg">
<line id="line" x1="50" y1="0" x2="200" y2="300"/>
</svg>
<button id="add">add</button>



</body>
</html>
3个回答

39

为了向SVG对象添加元素,这些元素必须在SVG命名空间中创建。由于jQuery目前(据我所知)不允许您执行此操作,因此无法使用jQuery来创建该元素。以下代码可行:

$("#add").click(function(){
    var newLine = document.createElementNS('http://www.w3.org/2000/svg','line');
    newLine.setAttribute('id','line2');
    newLine.setAttribute('x1','0');
    newLine.setAttribute('y1','0');
    newLine.setAttribute('x2','300');
    newLine.setAttribute('y2','300');
    $("#map").append(newLine);
});

这里有一个可运行的例子


2
从MDN:你(显然)应该使用DOM2方法,例如setAttributeNS(),详见命名空间XML中的脚本 - Trojan

12

用更少的代码实现

 $("#add").click(function(){
      $(document.createElementNS('http://www.w3.org/2000/svg','line')).attr({
          id:"line2",
          x1:0,
          y1:0,
          x2:300,
          y2:300
      }).appendTo("#map");

});

0

我通过读取SVG元素的innerHTML属性,然后将其写回SVG元素的innerHTML属性来解决了这个问题。这会强制进行元素刷新。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接