2011-09-25 8 views
11

Voglio aggiungere una nuova riga nello svg quando, viene premuto il pulsante aggiungi, una nuova riga deve essere aggiunta allo svg Sono sicuro che la linea sia aggiunto negli elementi, ma perché non viene visualizzato sullo schermo?aggiungi una nuova riga in svg, il bug non può vedere la riga

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

risposta

29

Per aggiungere elementi a un oggetto SVG, è necessario creare quegli elementi nello spazio dei nomi SVG. Poiché jQuery non ti permette di farlo al momento (AFAIK) non puoi usare jQuery per creare l'elemento. Funzionerà:

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

Da MDN: si (a quanto pare) dovrebbe usare [metodi DOM 2] (https://developer.mozilla.org/en-US/docs/Web/SVG/Namespaces_Crash_Course #Scripting_in_namespaced_XML) come 'setAttributeNS()' – Trojan

4

con poco meno codice

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

}); 
Problemi correlati