简体   繁体   中英

How do I append the text tag to just one svg e.g. svg tag with “id=50”?

How do I append the text tag to just one svg eg svg tag with "id=50"?

This code appends an svg tag to body with the following properties, and then appends text tag to each 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)

This code just appends text to the first svg( select ), FIDDLE here :

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

How do I append the text tag to just one svg eg svg tag with "id=50"?

This is my attempt:

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

I have also tried select("svg #50") but no joy. Can anyone advise?

Your problem is an invalid ID... you can't have an ID that starts with a number.

...
.attr("id",function(d){ return "id-"+d;})

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

You can have numeric ids in HTML5, using them as CSS selectors is harder though as they aren't valid identifiers there so #10 does not work .

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit...

You can work around CSS issues with numeric ids by using an attribute selector, or by encoding the initial digit as unicode as I've done below.

Having seen how painful this is going to be, you might well conclude that using numeric ids is a bad idea .

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM