如何将文本标签仅附加到一个svg,例如带有“id = 50”的svg标签?

时间:2016-06-15 02:41:13

标签: javascript d3.js svg

如何将文字标记附加到一个svg,例如带有“id = 50”的svg标签?

此代码将svg标记附加到具有以下属性的body,然后将text标记附加到每个svg(selectAll)。 FIDDLE here

var arr =[10,20,30,40,50]

//appends an svg tag to body with the following properties 
d3.select("body").selectAll("svg")
                 .data(arr)
                 .enter()
                 .append("svg")
                 .attr("width",201)
                 .attr("height",202)
                 .attr("id",function(d){ return d;})


//appends text tag to each svg 
d3.select("body").selectAll("svg").append("text")
         .attr("id",202)

此代码只是将文字附加到第一个svg(select),FIDDLE here

//appends text to the first svg 
d3.select("body").select("svg").append("text")
            .attr("id",202)

如何将文字标记附加到一个svg,例如带有“id = 50”的svg标签?

这是我的尝试:

d3.select("body").select("#50").append("text")
            .attr("id",202)

我也试过select("svg #50")但没有快乐。任何人都可以建议吗?

2 个答案:

答案 0 :(得分:3)

您的问题是无效的ID ...您不能拥有以数字开头的ID。

NSTimer

答案 1 :(得分:0)

您可以在HTML5中使用数字ID,因为CSS选择器更难,因为它们不是有效的标识符#10 does not work

  

在CSS中,标识符(包括选择器中的元素名称,类和ID)只能包含字符[a-zA-Z0-9]和ISO 10646字符U + 00A0及更高,加上连字符( - )和下划线(_);它们不能以数字,两个连字符或连字符后跟数字开头......

您可以使用属性选择器解决数字ID的CSS问题,或者将初始数字编码为unicode,如下所示。

看到这将会是多么痛苦,你可能会得出结论,使用数字ID是一个坏主意



var arr =[10,20,30,40,50]

//appends an svg tag to body with the following properties 
d3.select("body").selectAll("svg")
                 .data(arr)
                 .enter()
                 .append("svg")
                 .attr("width",201)
                 .attr("height",202)
                 .attr("id",function(d){ return d;})


d3.select("body").select('[id="20"]').append("text")
            .attr("id",202).attr("y", 50).text("hello")

d3.select("body").select('#\\31 0').append("text")
            .attr("id",203).attr("y", 80).text("again")

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<body></body>
&#13;
&#13;
&#13;