2013-09-05 111 views
1

我创建了一个标记以显示在行元素的末尾。但我的问题是,当标记标记是动态生成时,它不会显示在行的末尾。使用jquery动态生成标记时不显示标记

我所做的是首先将svg附加到html正文。

var svg = d3.select('body').append("svg").attr("width", 300).attr("height", 300).attr("id", "cloud"); 

然后我将标记添加到svg。

$('svg').append('<defs><marker id="arrow" viewbox="0 -5 10 10" refX="18" refY="0"markerWidth="6" markerHeight="6" orient="auto"><path d="M0,-5L10,0L0,5Z"></marker> </defs>'); 

然后我将行追加到svg属性marker-end指向svg标记元素。

svg.append("g").selectAll("line.link") 
     .data(force.links()) 
     .enter().append("line") 
     .attr("class", "link") 
     .attr("marker-end", "url(#arrow)"); 

标记不显示在行尾。 下面是代码的的jsfiddle http://jsfiddle.net/2NJ25/2/

链接但是,当我使用jQuery删除动态追加和我这样定义它下面在这里工作的代码的HTML中的标记标签是链接http://jsfiddle.net/AqK4L/4/

<!DOCTYPE html> 
<html> 
    <head> 
     <meta http-equiv="content-type" content="text/html;charset=utf-8"> 
     <title>Cloud</title> 
     <script type="text/javascript" src="d3.v2.js"></script> 
     <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> 
    </head> 
    <body> 
     <svg id="cloud" width="800" height="600"> 
      <defs> 
       <marker id="arrow" viewbox="0 -5 10 10" refX="18" refY="0" 
         markerWidth="6" markerHeight="6" orient="auto"> 
        <path d="M0,-5L10,0L0,5Z"> 
       </marker> 
      </defs> 
     </svg> 
     <link href="cloud.css" rel="stylesheet" type="text/css" /> 
     <script src="cloud.js" type="text/javascript"></script> 
    </body> 
</html> 

动态生成标记标记时会出现什么问题。为什么标记不显示?我想动态生成标记标记。这个怎么做?

回答

3

问题是,通过使用jQuery添加SVG元素作为文本,他们得到解释在错误的名称空间。也就是说,HTML中没有defs,等元素,因此他们什么都不做。这些元素仅在SVG命名空间中有效,您在动态添加SVG时不指定它们。当它们被静态指定时,命名空间在上下文中是显而易见的。

有几种方法可以解决这个问题。您可以使用正确的名称空间显式创建节点,并将它们添加到适当的位置。然而,更简单的解决方案是使用D3来添加这些元素,这将为您处理名称空间问题。代码会稍微冗长些,但很直接。

svg.append("defs").append("marker") 
    .attr("id", "arrow") 
    .attr("viewbox", "0 -5 10 10") 
    .attr("refX", 18) 
    .attr("refY", 0) 
    .attr("markerWidth", 6) 
    .attr("markerHeight", 6) 
    .attr("orient", "auto") 
    .append("path") 
    .attr("d", "M0,-5L10,0L0,5"); 

更新了jsfiddle here

+0

为什么即使使用D3它剧照中看不到?我如何显式声明名称空间? –

+0

很难说不知道你在做什么。 –

0

添加了一些代码。看看我的update

1)

var texts = svg.selectAll(".label") 
     .data(force.nodes())      
     .enter()    
     .append("text") 
      .attr("class", "label") 
      .attr("fill", "black") 
      .text(function(d) { return d.name; }) 
     .call(force.drag); 

2)

texts.attr("transform", function(d) { 
     return "translate(" + d.x + "," + d.y + ")"; 
    }); 

CSS

.node, .label { 
    cursor:pointer; 
}