如何在 <br> dom(vanilla JavaScript)上添加标签?我无法在新行上显示下一个循环


const start = document.getElementById("start");
const end = document.getElementById("end");
const btnShowEven = document.getElementById("showEven");
const display = document.getElementById("display");
const br = document.createElement("br");
btnShowEven.addEventListener("click", myFunction);
function myFunction() {
for (let i = start.value; i <= end.value; i++) {
if (i % 2 == 0) {
console.log(`${i} is an even number.`);
display.textContent += `${i} is an even number.`;
display.createElement += br;
}
}
}

如何添加
标签dom(香草javascript)?我不能在新行显示下一个循环。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="main.css" />
<title>Document</title>
</head>
<body>
<input type="text" id="start" />
<input type="text" id="end" />
<button id="showEven">Show even numbers</button>
<hr />
<p id="display"></p>
<script src="main.js"></script>
</body>
</html>

我是初学者。对不起。这是我的HTML文件。输出是我的循环在一行中显示的所有内容。我想在新行中显示所有偶数

这里有一个简单的解决方案。只要使用innerHTML,而不是尝试创建新的元素。

const start = document.getElementById("start");
const end = document.getElementById("end");
const btnShowEven = document.getElementById("showEven");
const display = document.getElementById("display");
const br = document.createElement("br");
btnShowEven.addEventListener("click", myFunction);
function myFunction() {
for (let i = start.value; i <= end.value; i++) {
if (i % 2 == 0) {
console.log(`${i} is an even number.`);
display.innerHTML += `${i} is an even number.<br>`;
}
}
}
<input value="1" id="start">
<input value="10" id="end">
<button id="showEven">Click</button>
<div id="display"></div>

您可以使用n来模拟<br>标记。如何使用它?这就是

display.innerText += '${i} is an even number. n';

最新更新