Javascript 如何使用D3.js在HTML元素中创建换行符

Javascript 如何使用D3.js在HTML元素中创建换行符,javascript,html,d3.js,Javascript,Html,D3.js,我似乎无法将工具提示格式化为4行。我有一个p元素,想把它分解。我已尝试添加br和\n,但它们似乎没有帮助 var tooltip = d3.select("body") .append("div") .attr('class', 'tooltip'); tooltip.append("p"); //在这里,我使用selectAll和append循环浏览我的数据。“.on”属性是当我将鼠标悬停在圆上时,希望看到工具提示 .on("mousemove", function(d){

我似乎无法将工具提示格式化为4行。我有一个p元素,想把它分解。我已尝试添加br和\n,但它们似乎没有帮助

var tooltip = d3.select("body")
    .append("div")
    .attr('class', 'tooltip');

tooltip.append("p");
//在这里,我使用selectAll和append循环浏览我的数据。“.on”属性是当我将鼠标悬停在圆上时,希望看到工具提示

.on("mousemove", function(d){

if (d.source == "target") {              
    tooltip.select("p").text(d.source);
} else {                       
    tooltip.select("p").text("Line 1: " + "this is line 1" + "\n" + "line 2: " + "this is line 2");
}

不要使用
.text()
,而是使用
.html()
,这样您就可以像这样使用

tooltip.select("p").html("Line1: this is line 1 <br> line 2: this is line 2");
tooltip.select(“p”).html(“第1行:这是第1行
第2行:这是第2行”);
如果这不起作用,试试看

tooltip.select("p").html(function(){
    return "Line 1: this is line 1 <br> line 2: this is line 2"
});
tooltip.select(“p”).html(函数(){
return“第1行:这是第1行
第2行:这是第2行” });

因为这就是我目前使用
.html()

的方式,只是作为对以下内容的补充:

您可以在此处使用
html()
text()
方法。它们之间的区别在于
text()
使用,而
html()
使用

我们可以在for
text()
中看到这一点:

这是for
html()

因此,每种方法都有其特殊性

使用html()

如前所述,您可以将
html()

一起使用:

d3.select(“p”).html(“第1行:“+”这是第1行“+”
“+”第2行:“+”这是第2行”)

this.textContent = value;
this.innerHTML = value;