2012-09-24 59 views
2

我有以下文档,在那里我打算添加一些水平线,每行一个文本框,其中行应该有一个“名称:数字”结构。追加孩子内嵌SVG使用javascript

<!DOCTYPE html> 
<html lang="pt-br" xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg"> 
<head> 
    <meta charset="UTF-8" /> 
    <meta http-equiv="pragma" content="no-cache"/>  
    <title>Diagrama Audax</title> 

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script> 
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script> 

    <style type="text/css"> 
     #sidebar {float: left; display: inline-block;} 
     #drawing {left: 330px; position: relative; display: inline-block} 
     #Locais {width: 300px; height: 500px;} 
     svg {background: #ddd; width: 500px; height: 500px;} 
     td, textarea {margin: 0; padding: 0;} 
    </style> 
</head> 

<body> 
    <table> 
     <tr id="tabela" cols="2"> 
      <td> 
       <textarea id="Locais"></textarea> 
      </td> 
      <td> 
       <svg id="svg"> 
        <circle stroke="black" fill="red" cx="200" cy="200" r="100" opacity="0.1"/> 
        <line id="path" x1="0" y1="0" x2="200" y2="200" stroke="black"/> 
       </svg> 
      </td> 
     </tr> 
    </table> 
</body> 

<script> 

    // A função abaixo pega a caixa de texto e associa o evento "draw" a ela 
    $(function() { 
     $("#Locais").keyup(function() { 
      valueString = $("#Locais").val(); 
      if (valueString != "") { 
       lines = valueString.replace("\r","").split("\n"); 
       CPs = []; 

       for (i in lines) { 
        eachLine = lines[i]; 
        tmpDict = {}; 
        values = eachLine.split(":"); 
        for (j in values) { 
         eachVal = values[j]; 
         tmpDict[j] = eachVal; 
        } 
        CPs.push(tmpDict); 
       } 
       DrawUsing(CPs); 
      } 
     }) 
    }); 


    function DrawUsing (lista) { 
     var svg = document.getElementById("svg"); 
     for (element in lista) { 
      refname = lista[element][0]; 
      refdist = lista[element][1]; 
      var line = document.createElement ("line"); 
      line.setAttribute('stroke', "black"); 
      line.setAttribute('stroke-width', 1); 
      line.setAttribute('x1', 0); 
      line.setAttribute('x2', 100); 
      line.setAttribute('y1', refdist); 
      line.setAttribute('y2', refdist); 
      svg.appendChild(line); 
      console.log(document.getElementsByTagName("line").length); 
     } 
    } 
</script> 
</html> 

作为一个“热身”,我试图操纵SVG每次按下按键时添加行。粘贴下面的文本(只需粘贴Ctrl + V就足以触发键盘事件),但尽管svg子列表增加了,但没有看到其他行。

我在做什么错? (很多,我想,因为我非常与JavaScript的n00b,并直接操纵内联<svg>元素(而不是<object>)是很差的文件,它似乎...

任何帮助是最受欢迎,谢谢你阅读!

回答

2

SVG元素在http://www.w3.org/2000/svg命名空间去所以不是

var line = document.createElement ("line"); 

使用

var line = document.createElementNS ("http://www.w3.org/2000/svg","line");