我有这段代码
.text(function(d){return d.name});
现在我想检查d.name的长度,如果超过10,则将其分成两行 我写了这段代码,但它不起作用
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);
答案 0 :(得分:0)
使用选择html
方法代替text
。所以:
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;
});
答案 1 :(得分:0)
你遗失了,if语句中有else
。
$(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);
}
});