我试图通过将字符串包装在tspan标记中来包装svg标签。
我的问题是当split()发生时属性不起作用。我的对象似乎不在函数内部工作,但它似乎在控制台中工作。 d.text在控制台中返回,但就在函数内部工作而言,某些东西已关闭。
function wrap(text, width) {
text.each(function (d) {
console.log("is d.text defined?" + d.text /* this gets returned ok - logs all the d.text*/)
wordwrap = ( function (){return "These are long labels" /*hardcoded label strings: this gets returned ok*/})
wordwrap = ( function (){return d.text; /* undefined is not a function */})
wordwrap = d.text; /* number is not a function */
var text = d3.select(this),
words = wordwrap().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
x = text.attr("x"),
y = text.attr("y"),
dy = 0, //parseFloat(text.attr("dy")),
tspan = text.text(null)
.append("tspan")
.attr("x", x)
.attr("y", y)
.attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan")
.attr("x", x)
.attr("y", y)
.attr("dy", ++lineNumber * lineHeight + dy + "em")
.text(word);
}
console.log(d.text) /* this gets returned ok*/
}
});
}