我正在编写一个代码,它接受用户输入的数字并生成从 0 到用户提供的任何数字作为输入的数字。 我已经编写了将 html 和 js 连接在一起的代码,但是它仍然没有执行我想要它执行的功能
我在 html 中创建了一个按钮元素,并使用 id 在 javscript 中链接它。生成的每个数字应该根据它是素数、偶数还是奇数而具有不同的背景颜色。 所以我有一个用于输入数字的输入元素和一个按钮,该按钮应该生成从 0 到输入的任何数字的数字。例如,如果输入 5,该按钮将生成数字 0-5,但该按钮不起作用。它只生成数字 0 并停止,我在控制台中没有收到任何错误。这是 JavaScript 代码:
const button = document.querySelector("button");
button.addEventListener("click", () => {
const num = document.querySelector("#number").textContent;
const userNum = parseInt(num, 10);
for (let i = 0; i <= num; i++) {
let container = document.createElement("div");
container.textContent = i;
// function to check if a number is a prime number
function isPrime(number) {
if (number <= 1) return false;
if (number <= 3) return true;
if (number % 2 === 0 || number % 3 === 0) return false;
for (let i = 5; i * i <= number; i += 6) {
if (number % i === 0 || number % (i + 2) === 0) return false;
}
return true;
}
if (isPrime(i)) {
container.style.backgroundColor = "red";
} else if (i % 2 === 0) {
container.style.backgroundColor = "green";
} else if (i % 2 !== 0) {
container.style.backgroundColor = "yellow";
}
let containerElement = document.querySelector("#numberContainer");
containerElement.appendChild(container);
} });
因为你使用
const num = document.querySelector("#number").textContent;
textContent 属性返回元素的文本内容,#number 元素是一个输入字段,它没有任何文本内容可返回。
所以 num 最终的值为 undefined。
相反,要获取用户在 #number 输入字段中输入的值,您需要使用 .value 属性:
const num = document.querySelector("#number").value;
另外,生成div时,需要将i转换为字符串来设置textContent,否则会强制转换为字符串,只显示“0”:
container.textContent = i.toString();
这是完整代码
const button = document.querySelector("button");
button.addEventListener("click", () => {
// Get user input correctly
const userNum = document.querySelector("#number").value;
for (let i = 0; i <= userNum; i++) {
let container = document.createElement("div");
// Convert i to string for textContent
container.textContent = i.toString();
// Check if prime
function isPrime(number) {
// prime check logic
}
if (isPrime(i)) {
container.style.backgroundColor = "red";
} else if (i % 2 === 0) {
container.style.backgroundColor = "green";
} else {
container.style.backgroundColor = "yellow";
}
let containerElement = document.querySelector("#numberContainer");
containerElement.appendChild(container);
}
});