2011-09-25 8 views
11

Quiero agregar una nueva línea en el svg cuando, se presiona el botón agregar, se debe agregar una nueva línea en svg Puedo asegurar que la línea es agregado en los elementos, pero ¿por qué no se muestra en la pantalla?agregar una nueva línea en svg, el error no puede ver la línea

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

Respuesta

29

Para agregar elementos a un objeto SVG, estos elementos deben crearse en el espacio de nombres SVG. Como jQuery no le permite hacer esto actualmente (AFAIK), no puede usar jQuery para crear el elemento. Esto funcionará:

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

Here's a working example.

+1

De MDN: que (aparentemente) debe utilizar [métodos DOM2] (https://developer.mozilla.org/en-US/docs/Web/SVG/Namespaces_Crash_Course #Scripting_in_namespaced_XML) como 'setAttributeNS()' – Trojan

4

con poco menos código

$("#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"); 

}); 
Cuestiones relacionadas