I have this code
.text(function(d){return d.name});
now I want to check length of the d.name if its more than 10 break it in two line I wrote this code but it doesn't work
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + source.x0 + "," + source.y0 + ")"; })
.on("click", click);
nodeEnter.append("circle")
.attr("r", 1e-6)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
var name1="asdsdadasdasdas";
nodeEnter.append("text")
.attr("x", function(d) { return d.children || d._children ? -40 : -25; })
.attr("dy",function(d){return d.children || d._children ? "-2em" : "2em"})
.attr("text-anchor", "end")
.attr("height",50)
.attr("width",50)
.text(function(d){
var str=d.name;
if(str.length>10){
var txt1=str.slice(0,10);
txt1+="<br/>";
txt2=str.slice(10,str.length);
return txt1+txt2;
}else{
return d.name;
}
})
.attr("transform",function(d){
return "rotate(45)";
})
.style("fill-opacity", 1e-6);
Use the selection html
method instead of text
. So:
selection.html(function(d){
var str=d.name;
if(str.length>10){
var txt1=str.slice(0,10);
txt1+="<br/>";
txt2=str.slice(10,str.length);
return txt1+txt2;
}
return d.name;
});
you are missing, else
in if statement.
$(document).ready(function () {
var str = 'somelongtesxtthat';
if (str.length > 10) {
var txt1 = str.slice(0, 10);
txt1 += "<br/>";
var txt2 = str.slice(10, str.length);
alert(txt1 + txt2);
} else {
alert(str);
}
});
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.