1

我创建了一个网站,它会告诉你你的年龄。我使用 document.createTextNode 来存储输出,但输出无法正常工作。这是输出代码

var h1 = document.createElement("p");
h1.setAttribute("id", "mainText")
var mainText = document.createTextNode("You are ", ageYears, " years, ", ageMonths, " 
months and ", ageDays, " days old.");
h1.appendChild(mainText);
document.getElementById("new-age").appendChild(h1);

当我运行我的代码时,它只输出第一部分,“你是”。有没有办法输出整个消息。

4

2 回答 2

1

由于document.createTextNode只接收一个参数作为数据,您应该更改document.createTextNode下面的代码以使用您的数据生成一个字符串:(在您的代码中,因为您,用于连接字符串,实际上您正在传递多个字符串document.createTextNode,它只读取第一个参数和忽略其他论点)

var mainText = document.createTextNode("You are " + ageYears + " years, " + ageMonths + "months and " + ageDays + " days old.");

或者:

var mainText = document.createTextNode(`You are ${ ageYears} years, ${ageMonths} months and ${ageDays} days old.`);

这是一个例子:

const ageYears = 30;
const ageMonths = 10;
const ageDays = 22;

function appendText() {
  let p = document.createElement("p");
  let mainText = document.createTextNode(`You are ${ ageYears} years, ${ageMonths} months and ${ageDays} days old.`);

  p.appendChild(mainText);
  document.getElementById("new-age").appendChild(p);
}

document.getElementById('appendBtn').addEventListener('click', appendText)
<div id="new-age"></div>
<button id="appendBtn">append text</button>

于 2021-12-18T09:02:49.230 回答
1

在 JavaScript 中,您使用+而不是.连接字符串。

工作示例

var h1 = document.createElement("p");
h1.setAttribute("id", "mainText");
let ageYears = 20;
let ageMonths = 12
let ageDays = 24;
var mainText = document.createTextNode("You are " + ageYears + " years, " + ageMonths  + " months and " + ageDays + " days old.");
h1.appendChild(mainText);
document.getElementById("new-age").appendChild(h1);
<div id="new-age"></div>

于 2021-12-18T09:11:48.853 回答