英文:
Why is this just printing out hello world 9 times instead of adding the event onclick?
问题
以下是代码的翻译部分:
let number1 = document.getElementById("number1");
let number2 = document.getElementById("number2");
let number3 = document.getElementById("number3");
let number4 = document.getElementById("number4");
let number5 = document.getElementById("number5");
let number6 = document.getElementById("number6");
let number7 = document.getElementById("number7");
let number8 = document.getElementById("number8");
let number9 = document.getElementById("number9");
let number0 = document.getElementById("number0");
const numbers_ = [number0, number1, number3, number4, number5, number6,
number7, number8, number9];
function myfunction() {
console.log("hello world");
};
numbers_.forEach(num => {
num.addEventListener("click", myfunction)
});
请注意,我已经将HTML实体(如"
)转换为正常的引号(" "),以使代码正确运行。
英文:
let number1 = document.getElementById("number1");
let number2 = document.getElementById("number2");
let number3 = document.getElementById("number3");
let number4 = document.getElementById("number4");
let number5 = document.getElementById("number5");
let number6 = document.getElementById("number6");
let number7 = document.getElementById("number7");
let number8 = document.getElementById("number8");
let number9 = document.getElementById("number9");
let number0 = document.getElementById("number0");
const numbers_ = [number0, number1, number3, number4, number5, number6,
number7, number8, number9]
function myfunction() {
console.log("hello world");
};
numbers_.forEach(num => {
num.addEventListener("click", myfunction())
});
This is my code. It is just logging Hello World 9 times on load instead of waiting for the click. Please help.
答案1
得分: 6
因为你调用了一个函数而不是只传递它。
应该是:
numbers_.forEach(num => {
num.addEventListener("click", myfunction)
});
英文:
Because you called a function instead of just pass it.
Should be:
numbers_.forEach(num => {
num.addEventListener("click", myfunction)
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论